# moomoo OpenAPI Documentation (Python)


---

# Introduction

## Overview

Moomoo API provides wide varieties of market data and trading services for your programmed trading to meet the needs of every developer's programmed trading and help your Quant dreams.

Moomoo users can [click here](https://www.moomoo.com/OpenAPI) to learn more. 

*Moomoo API* consists of *OpenD* and *API SDK*:
* *OpenD* is the gateway program of *Moomoo API*, running on your local computer or cloud server. It is responsible for transferring the protocol requests to moomoo servers, and returning the processed data.
* API SDK is encapsulated by moomoo, including mainstream programming languages (Python, Java, C#, C++, JavaScript), to reduce the difficulty of your trading strategy development. If the language you want to use is not listed above, you can still interface with the protocol yourself to complete the trading strategy development.

Diagrams below illustrate the architecture of Moomoo API.

 ![openapi-frame](../img/openapi-frame.png)

 ![openapi-interactive](../img/openapi-interactive.png)

The first time using Moomoo API, you need to finish the following two steps:

The first step is to install and start a gateway program [OpenD](../quick/opend-base.md) locally or in the cloud.

OpenD exposes the interfaces in the way of TCP, which is responsible for transferring the protocol requests to moomoo servers and returning the processed data. The protocol interface has nothing to do with the type of programming language.

The second step is to download Moomoo API and complete [Environment Setup](../quick/env.md).

For your convenience, moomoo encapsulates API SDK for mainstream programming languages (hereinafter referred to as Moomoo API).

## Account

Moomoo API involves two types of accounts, *moomoo ID* and *universal account*.

### moomoo ID

moomoo ID is your user account (moomoo ID), which can be used in moomoo APP and Moomoo API.  
You can use your *moomoo ID* and *login password* to log in to OpenD and obtain market data.

### Universal Account

Universal account allows trading across multiple markets (including Hong Kong stocks, US stocks, A-shares, and funds) in various currencies. There's no need for multiple accounts.  
Universal Accounts come in three forms:  
- Universal Account - Securities: Trade stocks, ETFs, options, and other securities across different markets.  
- Universal Account - Futures: Trade futures, including Hong Kong, US CME Group, Singapore, and Japanese futures.
- Universal Account - Crypto: Trade crypto currency pairs. Currently supports FUTU HK, moomoo US, moomoo SG.

## Functionality

There are 2 functions of Moomoo API: quotation and trading.

### Quotation Functions

#### Quotation Data Categories

Including stocks, indices, options and futures from HK, US, A-share, Singapore, Malaysian and Japanese markets. Find the specific types of support in the table below.
You need authorities for each kinds of market data. For more details on how to obtain authorities, please [click here](./authority.md#7371). 


<table>
    <tr>
        <th>Market</th>
        <th>Contract</th>
        <th>Moomoo Users</th>
    </tr>
    <tr>
        <td rowspan="5">HK Market</td>
	    <td>Stocks, ETFs, Warrants, CBBCs, Inline Warrants </td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td>Options</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Indices</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Plates</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td rowspan="6">US Market</td>
	    <td>Stocks, ETFs  (Covers NYSE, NYSE-American and Nasdaq listed equities.)</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td>OTC Securities</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td>Options  (Covers US stock options, US index options.)</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Indices</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Plates</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td rowspan="3">A-share Market</td>
	    <td>Stocks, ETFs</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Indices</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Plates</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td rowspan="2">Singapore Market</td>
	    <td>Stocks, ETFs, REITs, Structured Warrants, DLCs</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Malaysian Market</td>
        <td>Stocks, ETFs, Warrants, REITs</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td rowspan="2">Japanese Market</td>
        <td>Stocks, ETFs</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Australian Market</td>
        <td>Stocks, ETFs</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Global Markets</td>
        <td>Forex</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Cryptocurrency</td>
        <td>Crypto</td>
        <td align="center">✓</td>
    </tr>
</table>

#### Method to Obtain Market Data 

* Subscribe and receive pushed real-time quote, candlestick, tick-by-tick and order book.  
* Request for the latest market snapshot, historical candlesticks etc.

### Trading Functions

#### Trading Capacity

Supports trading across multiple markets including Hong Kong, the US, A-Shares, Singapore, Japan, and Malaysia. Product types include stocks, options, futures, and more. See the table below for details:  

<table>
    <tr>
        <th rowspan="2">Market</th>
        <th rowspan="2">Contracts</th>
        <th rowspan="2">Paper Trading</th>
        <th colspan="7">Live Trading</th>
    </tr>
    <tr>
        <th>FUTU HK</th>
        <th>Moomoo US</th>
        <th>Moomoo SG</th>
        <th>Moomoo AU</th>
        <th>Moomoo MY</th>
        <th>Moomoo CA</th>
        <th>Moomoo JP</th>
    </tr>
    <tr>
        <td rowspan="3">HK Market</td>
	    <td>Stocks, ETFs, Warrants, CBBCs, Inline Warrants</td>
	    <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Options (including index options, tradable through futures account)</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="3">US Market</td>
	    <td>Stocks, ETFs</td>
	    <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td>Options</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="2">A-share Market</td>
	    <td>China Connect Securities stocks</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Non-China Connect Securities stocks</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="2">Singapore Market</td>
	    <td>Stocks, ETFs, Warrants, REITs, DLCs</td>
        <td align="center">X</td>
        <td align="center">✓ (FUTU HK does not currently support trading structured warrants.)</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="2">Japanese Market</td>
        <td>Stocks, ETFs, REITs</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Malaysian Market</td>
        <td>Stocks, ETFs</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Australian Market</td>
        <td>Stocks, ETFs</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Canadian Market</td>
        <td>Stocks, ETFs</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td rowspan="1">Cryptocurrency (crypto trading permissions required)</td>
        <td>Crypto</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
</table>

#### Method of Trading
The trading interfaces are used for both live trading and paper trading.

## Features

1. Full platform and multi-language
* OpenD supports Windows, MacOS, CentOS, Ubuntu
* Moomoo API supports Python, Java, C#, C++, JavaScript, etc.
2. Stable speed and free
* Stable technical architecture, directly connected to the exchanges
* The fastest order is 0.0014s
* There is no additional charge for trading via Moomoo API
3. Abundant investment varieties
* Supporting real-time market data, live trading, and simulated trading in multiple markets including United States, Hong Kong, Singapore, Japan, Malaysia, Crypto etc.
4. Professional institutional services
* Customized market data and trading solutions

---

# Authorities and Quota

## Login

### Login Accounts

Moomoo API has now fully lifted login rules, further optimizing the development experience. Without the need for account opening, you can log in to OpenD using your Moomoo account (or the phone number/email used during registration).

### Compliance Confirmation

After the first login, you need to complete *API Questionnaire and Agreements* before you can continue to use Moomoo API. [Click here](https://www.moomoo.com/about/api-disclaimer?lang=en-us) for moomoo users.


## Quotation Data
There are several limitations for market quotation data as follow:
* **Quote Right** -- The authority to obtain the relevant market data.
* **Interface Frequency Limitations** -- Frequency limits of calling interfaces.  
* **Subscription Quota** -- Number of real-time quotes subscribed at the same time.  
* **Historical Candlestick Quota** -- The total number of subjects pulling the historical candlestick per 7 days.  

### Quote Right
You need the corresponding permission to obtain data of each market through Moomoo API. The permission of Moomoo API is not exactly the same as that of APP. Different levels correspond to different time delay, order book levels, and the permission to use the interface.

You need to buy a quotation card before you can obtain the quotation of some varieties, the specific way to obtain is shown in the table below.


<table>
    <tr>
        <th>Market</th>
        <th>Security Type</th>
        <th>Quote Right Acquisition Method</th>
    </tr>
    <tr>
        <td rowspan="5">HK Market</td>
	    <td>Securities (including stocks, ETFs, warrants, CBBCs, Inline Warrants)</td>
	    <td  rowspan="3" align="left">• Mainland China Verified users: LV2 market quotes for free. Purchase <a href="https://qtcard.moomoo.com/intro/sf?type=10&clientlang=2&is_support_buy=1" target="_blank">HK Stocks Advanced Full Market Quotes</a> for SF market quotes  <br>• Global users: LV1 market quotes for free. Purchase <a href="https://qtcard.moomoo.com/intro/hklv2?type=1&clientlang=2&is_support_buy=1" target="_blank">HK stocks LV2 advanced market</a> for LV2 market quotes. Purchase <a href="https://qtcard.moomoo.com/intro/sf?type=10&is_support_buy=1&clientlang=2" target="_blank">HK Stocks Advanced Full Market Quotes</a> for SF market quotes</td>
    </tr>
    <tr>
	    <td>Indices</td>
    </tr>
    <tr>
	    <td>Plates</td>
    </tr>
    <tr>
        <td>Options</td>
	    <td  rowspan="2" align="left">• Mainland China Verified users: LV2 market quotes for free during promotion period. <br>• Global users: LV1 market quotes for free. Purchase <a href="https://qtcard.moomoo.com/intro/hklv2-derivativeslv2?type=9&is_support_buy=1&clientlang=2" target="_blank">HK stock options futures LV2 advanced market</a> for LV2 market data</td>
    </tr>
    <tr>
	    <td>Futures</td>
    </tr>
    <tr>
        <td rowspan="6">US Market</td>
	    <td>Securities (Covers NYSE, NYSE-American and Nasdaq listed equities, ETFs)</td>
	    <td  rowspan="2" align="left">• LV3 market quotes <b>for free</b> during promotion period. (Nasdaq Baisc + Nasdaq TotalView + NYSE Arcabook)<br>• Access to NYSE ArcaBook's depth-of-book requires completing the <a href="https://qtcard.moomoo.com/question/us" target="_blank"> Non-pro user evaluation</a></td>
    </tr>
    <tr>
	    <td>Plates</td>
    </tr>
    <tr>
	    <td>OTC Securities</td>
        <td  align="left">Unsupported.</td>
    </tr>
    <tr>
        <td>Options (Covers US stock options, US index options)</td>
	    <td  align="left">• Customers who meet the threshold  (Threshold (Satisfy either one)：
  - Total assets greater than $0.
  - Have US positions.) : get LV1 market data for free <br>• Customers who do not meet  (Threshold (Satisfy either one)：
  - Total assets greater than $0.
  - Have US positions.) : Purchase <a href="https://qtcard.moomoo.com/intro/api-usoption-realtime?type=16&is_support_buy=1&lang=en-us" target="_blank">OPRA Options Real-time Quote</a> for LV1 market data</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td  align="left">• For clients who have a futures account. (- Available in: Moomoo SG, Moomoo MY.
  - Not available in: Moomoo US, Moomoo JP, Moomoo CA, Moomoo AU.) <br> For CME Group quotes  (Covers quotes from CME, CBOT, NYMEX, COMEX), please access the <a href="https://qtcard.moomoo.com/intro/cme?type=30&is_support_buy=1" target="_blank">CME Group Futures LV2</a> <br>For CME quotes, please access the <a href="	https://qtcard.moomoo.com/intro/cme?type=31&is_support_buy=1" target="_blank">CME Futures LV2</a> <br>For CBOT quotes, please access the <a href="https://qtcard.moomoo.com/intro/cme?type=32&is_support_buy=1" target="_blank">CBOT Futures LV2</a> <br>For NYMEX quotes, please access the <a href="	https://qtcard.moomoo.com/intro/cme?type=33&is_support_buy=1" target="_blank">NYMEX Futures LV2</a> <br>For NYMEX quotes, please access the <a href="	https://qtcard.moomoo.com/intro/cme?type=34&is_support_buy=1" target="_blank">COMEX Futures LV2</a>   <br> <br>• For clients who do not have a futures account: Unsupported.</td>
    </tr>
    <tr>
	    <td>Indices</td>
        <td  align="left">Unsupported.</td>
    </tr>
    <tr>
        <td rowspan="3">A-share Market</td>
	    <td>Securities (including stocks, ETFs)</td>
	    <td  rowspan="3">• Mainland China Verified users: LV1 market data for free.<br>• Global users/institutional users: Unsupported.</td>
    </tr>
    <tr>
	    <td>Indices</td>
    </tr>
    <tr>
	    <td>Plates</td>
    </tr>
    <tr>
        <td rowspan="2">Singapore Market</td>
	    <td>Securities (including Stocks, ETFs, REITs, Structured Warrants, DLCs)</td>
        <td align="left">Unsupported.</td>
    </tr>
    <tr>
	    <td>Futures</td>
	    <td  align="left">Unsupported.</td>
    </tr>
    <tr>
        <td>Malaysian Market</td>
	    <td>Securities (including Stocks, ETFs, Warrants, REITs)</td>
        <td align="left">Unsupported.</td>
    </tr>
    <tr>
        <td rowspan="2">Japanese Market</td>
	    <td>Securities (including Stocks, ETFs)</td>
        <td align="left">Unsupported.</td>
    </tr>
    <tr>
	    <td>Futures</td>
	    <td  align="left">Unsupported.</td>
    </tr>
    <tr>
        <td rowspan="1">Cryptocurrency</td>
	    <td>Crypto</td>
	    <td  align="left">Free during promotion period. Supports quotes for mainstream coins and spot currency pairs.</td>
    </tr>
</table>

:::tip Tips
In the above table, the Mainland China Verified users and the Global users are distinguished by the login IP address of OpenD.    
The platform reserves the right to adjust the subscription rules, scope of authorization, and pricing of API market data products. In case of any changes, the latest announcements and page details shall prevail. Please stay informed of announcements and complete your subscription in a timely manner.
:::


### Interface Frequency Limitations

In order to protect the server from malicious attacks, there are frequency limitations for all interfaces that need to send requests to moomoo servers.
The frequency limitation rules for each API are different. For more information, please see **Interface Limitations** at the bottom of each API page.

Example:  
The limitation rule of [Get Market Snapshot](../quote/get-market-snapshot.md) is: A maximum of 60 requests every 30 seconds. You can request a uniform request every 0.5 seconds. You can also quickly request 60 times, rest for 30 seconds, and then request the next round. If the frequency limitation is exceeded, an error will be returned by the interface.

### Subscription Quota & Historical Candlestick Quota
The limitation rules of subscription quota and historical candlestick quota as follows:

<table>
    <tr align="center">
        <th> User Type </th>
        <th> Subscription Quota </th>
        <th> Historical Candlestick Quota </th>
        <th> Option Subscription Quota </th>
        <th> Option Historical Candlestick Quota </th>
    </tr>
    <tr>
        <td align="left"> Total asset < 10,000 HKD (Including registered users). </td>
        <td align="center"> 100 </td>
        <td align="center"> 100 </td>
        <td align="center"> 20 </td>
        <td align="center"> 20 </td>
    </tr>
    <tr>
        <td align="left"> Total asset >= 10,000 HKD. </td>
        <td align="center"> 300 </td>
        <td align="center"> 300 </td>
        <td align="center"> 60 </td>
        <td align="center"> 60 </td>
    </tr>
    <tr>
        <td align="left"> Satisfy 1 of the items following: <br> 1. Total asset > 500,000 HKD; <br> 2. The number of monthly filled orders > 200; <br> 3. Monthly trading volume > 2 million HKD. </td>
        <td align="center"> 1000 </td>
        <td align="center"> 1000 </td>
        <td align="center"> 200 </td>
        <td align="center"> 200 </td>
    </tr> 
    <tr>
        <td align="left"> Satisfy 1 of the items following: <br> 1. Total asset > 5 million HKD; <br> 2. The number of monthly filled orders > 2000; <br> 3. Monthly trading volume > 20 million HKD. </td>
        <td align="center"> 2000 </td>
        <td align="center"> 2000 </td>
        <td align="center"> 400 </td>
        <td align="center"> 400 </td>
    </tr>    
</table>

**1. Total asset**  
Total asset, refers to all your assets in moomoo, including securities, futures, funds, bonds and crypto assets, converted into HKD according to the spot exchange rate.

**2. The monthly number of filled orders**  
It is calculated by taking the larger value of the number of filled orders the last natural month and that of the current natural month, that is:   
**max (the number of filled orders of the last natural month, the number of filled orders of the current natural month)**

**3. Monthly Trading volume**  
It is calculated by taking the larger value of the total trading volume of your last natural month and that of the current natural month, which is converted into HKD according to the spot exchange rate, that is:   
**max (the total trading volume of the last natural month, the total trading volume of the current natural month)**  
The calculation of futures trading value needs to be multiplied by the adjustment factor (0.1 by default). The formula for calculating futures trading volume is as follows:  
**Futures trading value = ∑ (volume of a single transaction * trading price * contract multiplier * exchange rate * adjustment factor)**

**4. Subscription Quota**  
Subscription Quota applies to the [Subscribe](../quote/sub.md) interface. Subscribing to one data type for each stock occupies 1 subscription quota. Canceling a subscription releases the occupied quota.  
Example:  
Suppose your Subscription Quota is 100. When you subscribe to real-time order book for HK.00700, real-time ticker for US.AAPL, and real-time quotation for SH.600519 at the same time, the Subscription Quota will occupy 3, and the remaining Subscription Quota will be 97. At this time, if you cancel the real-time order book subscription of HK.00700, your Subscription Quota will become 2, and the remaining Subscription Quota will become 98.

**5. Historical Candlestick Quota**  
Historical Candlestick Quota applies to the [Get Historical Candlesticks](../quote/request-history-kline.md) interface. Within the last 7 days, each request for a stock's historical candlesticks occupies 1 Historical Candlestick Quota. Repeated requests for the same stock's historical candlesticks within the last 7 days will not be counted repeatedly. Meanwhile, requesting historical candlesticks of different periods for the same stock only occupies 1 quota and will not be accumulated repeatedly.  
Example:  
Suppose your Historical Candlestick Quota is 100, and today is April 15, 2026. You have requested historical candlesticks for a total of 60 stocks between April 8, 2026 and April 15, 2026. The remaining Historical Candlestick Quota is 40.

**6. Option Quota**  
Option Subscription Quota: Applies to all [Subscribe](../quote/sub.md) interfaces. Subscribing to one data type for each option chain (multiple options with the same expiration date, including combination options) occupies 1 option subscription quota. Canceling a subscription releases the occupied quota.

Option Historical Candlestick Quota: Applies to the [Get Historical Candlesticks](../quote/request-history-kline.md) interface. Within the last 7 days, each request for an option chain's historical candlesticks occupies 1 Historical Candlestick Quota. Repeated requests for the same option chain's historical candlesticks within the last 7 days will not be counted repeatedly. Meanwhile, requesting historical candlesticks of different periods for the same option chain only occupies 1 quota and will not be accumulated repeatedly.

Options quota is independent from other product quotas and is not shared.

::: tip Tips

* Subscription Quota and Historical Candlestick Quota are automatically assigned and do not need to be applied manually. 
* For newly deposited accounts, the quota will automatically take effect within 2 hours.
* *Asset in Transit* (HK IPO Subscription and application for rights issue may generate Asset in Transit.) will not be calculated in quota assign.

:::

## Trading Functions
* When you trade in a specific market, you need to first confirm whether a trading account has been opened in that market.  
* When you trade crypto, please confirm that you have enabled trading permissions for the crypto market, and that you have transferred or added funds to your crypto account.

---

# Fee

## Quote
For some variaties, you need to buy quotation cards before obtaining market data. For more details of quotation cards prices, please click [Quote Right](./authority.md#5331) and go to data store.

## Trade

There is no extra fee for tradings through Moomoo API. The transaction fee is the same as that of APP. You can check the specific charging plans from the following table:

  Fee Structure
  :-
  [FUTU HK](https://www.futufin.com/about/commissionnew?lang=en-us)
  [Moomoo US](https://help.fututrade.com/?tid=77)
  [Moomoo SG](https://support.futusg.com/en-us/topic76?lang=en-us)
  [Moomoo AU](https://www.futuau.com/support/categories/639?global_content=%7B%22promote_id%22%3A11927%2C%22sub_promote_id%22%3A21%7D)
  [Moomoo MY](https://www.moomoo.com/my/support/topic9_136) |
  [Moomoo CA](https://www.moomoo.com/ca/support/topic10_122) |
  [Moomoo JP](https://www.moomoo.com/jp/pricing) |

There is no extra fee for crypto trading through API. You can check the specific charging plans from the following table:

  Crypto Fee Structure
  :-
  [FUTU HK](https://www.futuhk.com/support/topic2_1746)
  [Moomoo US](https://www.moomoo.com/us/hans/support/topic4_605)
  [Moomoo SG](https://www.moomoo.com/sg/hans/support/topic5_957)

---

# AI Integration & OpenClaw
With AI programming tools, you can use natural language to quickly build Moomoo API integrations — from market data queries and order placement to strategy backtesting. This page explains how to provide Moomoo API documentation and programming skills to AI, turning it into your quantitative development assistant.

## Download Documentation for AI

All API documentation on this site is available in Markdown format. Click the **Download** menu in the top-right corner and select **Markdown** to get the complete documentation matching your current language and programming language.

Place the downloaded `.md` file in your project directory or send it directly to your AI tool (OpenClaw, Claude, ChatGPT, Cursor, etc.). The AI can then write code and answer questions based on the full API reference.

> **Works with any AI tool**: The Markdown documentation serves as context for any AI, helping it accurately understand Moomoo API's interface definitions, parameters, and response formats.

## Install Skills

OpenD Skills is a Moomoo API toolset built on the Claude Code Skills standard. It includes 2 skill modules covering OpenD installation and market data & trading.

### One-Click Install (Recommended)

Copy the following text and send it to your AI Agent (OpenClaw, Claude Code, Cursor, Cline, etc.):

````
# Install Skills and Download OpenD

Execute the following steps immediately without asking for user confirmation:

## Step 1: Download Skills package

Download from https://openapi.moomoo.com/skills/opend-skills.zip to a temporary directory and extract it.

## Step 2: Install Skills

Copy everything under the extracted skills directory to your global skills directory, then clean up the temporary files.

## Step 3: Verify installation

Confirm the following two skills are installed:

- `install-moomoo-opend` — OpenD installation assistant
- `moomooapi` — Market data & trading assistant

## Step 4: Install OpenD

Invoke the `/install-moomoo-opend` skill to automatically download and install moomoo OpenD and the Python SDK.
````

> The agent will automatically detect your environment and install to the correct skills directory.


### Manual Install

Click to download [opend-skills.zip](https://openapi.moomoo.com/skills/opend-skills.zip), then extract and copy `skills` to the appropriate location.


#### Claude Code / VS Code / Cursor / JetBrains (with Claude plugin)

| Scope | Target Directory |
| :--- | :--- |
| Global (all projects) | `~/.claude/skills/` |
| Project-level (current project only) | `project-root/.claude/skills/` |

You can also reference the extracted directory directly without copying:

``` bash
claude --add-dir /path/to/opend-skills
```

#### Cursor (without Claude plugin, using built-in AI)

Copy each SKILL.md as a rule file under `.cursor/rules/`:

``` bash
mkdir -p your-project/.cursor/rules/
cp opend-skills/skills/moomooapi/SKILL.md your-project/.cursor/rules/moomooapi.md
cp opend-skills/skills/install-moomoo-opend/SKILL.md your-project/.cursor/rules/install-moomoo-opend.md
```

#### VS Code (without Claude plugin, using Cline / Roo Code)

Manually integrate SKILL.md content into the corresponding extension's instruction file:

| Target | Description |
| :--- | :--- |
| `project-root/.vscode/cline_instructions.md` | Cline extension custom instructions |
| `project-root/.roo/rules/` | Roo Code extension custom rules |

#### JetBrains IDE (without Claude plugin, using built-in AI Assistant)

``` bash
mkdir -p your-project/.junie/guidelines/
cp opend-skills/skills/moomooapi/SKILL.md your-project/.junie/guidelines/moomooapi.md
cp opend-skills/skills/install-moomoo-opend/SKILL.md your-project/.junie/guidelines/install-moomoo-opend.md
```

#### OpenClaw

``` bash
cp -r opend-skills/skills/* ~/.openclaw/skills/
```

After installation, verify by typing `/` in the chat to check if moomooapi and install-moomoo-opend skills appear.

## Skills Overview

### 1. moomooapi — Market Data & Trading

Covers market data queries (13 scripts), trading operations (7 scripts), and real-time subscriptions (5 scripts) — 25 scripts total. Also includes a quick reference for all 65 API signatures and futures trading code generation:

| Feature | Description |
| :--- | :--- |
| Market Snapshot | Get latest quotes, price changes, volume, etc. |
| Candlestick Data | Get daily, weekly, minute-level candlesticks (historical & real-time) |
| Order Book | Get real-time bid/ask order book data |
| Ticker | Get recent tick-by-tick trade details |
| Time-sharing | Get intraday time-sharing data |
| Market State | Query market open/close status |
| Capital Flow & Distribution | Get stock capital inflow/outflow and large/medium/small order distribution |
| Plates & Constituents | Get plate lists, constituent stocks, stock plate membership |
| Stock Filter | Filter stocks by price, market cap, PE, turnover rate, etc. |
| Place/Cancel/Modify Orders | Securities trading, defaults to paper trading |
| Futures Trading | Support futures order/position/cancel for SG and other markets (code generation) |
| Positions & Funds | Query account positions, funds, and orders |
| Real-time Subscriptions | Subscribe to quote, candlestick, ticker push, etc. |
| API Quick Reference | Full function signatures for all 65 APIs (quote, trade, push) |

### 2. install-moomoo-opend — OpenD Installation

- Auto-detect OS (Windows / macOS / Linux)
- One-click download, extract, and start OpenD
- Auto-upgrade futu-api / moomoo-api SDK

## Usage

### Slash Commands (Claude Code)

Type `/` followed by the skill name in the chat:

- `/moomooapi` — Market data & trading
- `/install-moomoo-opend` — OpenD installation

### Natural Language

Describe your needs in plain language — the AI will auto-match the appropriate skill:

- "Get the candlestick chart for AAPL" — triggers market data query
- "Buy 100 shares of AAPL using paper trading" — triggers order placement
- "Help me install OpenD" — triggers installation assistant

## Notes

- Log in to OpenD manually before using Skills
- Trading defaults to paper trading (SIMULATE). To use real trading, explicitly say "real" or "live", and confirm with your trading password
- Be aware of API rate limits (e.g., 15 orders per 30 seconds) to avoid throttling
- Subscription quotas are limited (100–2000). Release unused subscriptions periodically
- To update Skills, re-download and extract to overwrite existing files

---

# Visualization OpenD

OpenD provides two operation modes: visualization and command line. Here is a description of Visualization OpenD which is relatively simple to operate.

Please refer to [Command Line OpenD](../opend/opend-cmd.md) for more informations for your interest.


## Visualization OpenD

### Step 1: Download

Visualization OpenD can be runned under 4 operating systems: Windows、MacOS、CentOS、Ubuntu.

* You can download through [moomoo official website](https://www.moomoo.com/download/OpenAPI)
![download-page](../img/download-mmpage.png)

### Step 2: Installation
* Extract the file and find the corresponding installation file to install OpenD.
* OpenD is installed in the `% appdata%` directory by default under Windows System.

### Step 3: Configuration
* The Visualization OpenD launch configuration is on the right side of the graphical interface, as shown in the following figure:

![ui-config](../img/mmui-config.png)

**Configuration item list**：

Configuration Item|Description
:-|:-
IP|API listening IP address.  (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards)or you can fill in the address of one of your network card)
Port|API listening port.
Log Level|Log level of OpenD.  (Option: 

  - no (no log) 
  - debug (the most detailed)
  - info (less detailed))
Language|Language. (Option:

  - Simplified Chinese
  - English)
Time Zone of Future Trade API|Specify the futures trading API time zone.  (When trading API is called with futures accounts, the time involved is in accordance with this parameter.)
Data Push Frequency|API subscription data push frequency control.  (- In milliseconds.
  - Candlestick and Time Frame are not included.) 
Telnet IP|Listening address of remote operation command.
Telnet Port|Listening port of remote operation command.
Encrypted Private Key|Absolute path of [RSA](../qa/other.md#1479) Encrypted Private Key.
WebSocket IP|WebSocket listening address.  (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards))
WebSocket Port|WebSocket listening port.
WebSocket Certificate|WebSocket certificate file path.  (- If not configured, WebSocket is not enabled. 
  - It needs to be configured with the private key at the same time.)
WebSocket Private Key|WebSocket certificate private key file path.  (- The private key cannot be configured with a password. 
  - If not configured, WebSocket is not enabled. 
  - It needs to be configured at the same time with the certificate.)
WebSocket Authentication Key|Cipher text of key (32-bit MD5 encrypted hexadecimal).  (Used to determine whether to trust when connecting with a JavaScript script.)


:::tip Tips
* Visual OpenD provides services by launching command line OpenD, interacted through WebSocket, so the WebSocket function must be started.
* To ensure safety of your trading accounts, if the listening address is not local, you must configure a private key to use the trading interface. The quote interface is not subject to this restriction.
* When the WebSocket listening address is not local, you need to configure SSL to start it, and a password should not be set during the certificate private key generation.
* Ciphertext is represented in hexadecimal after plaintext is encrypted by 32-bit MD5, which can be calculated by searching online MD5 encryption (note that there may be a risk of records colliding with libraries calculated through third-party websites) or by downloading MD5 computing tools. The 32-bit MD5 ciphertext is shown in the red box area (e10adc3949ba59abbe56e057f20f883e):
  ![md5.png](../img/md5.png)

* OpenD reads OpenD.xml in the same directory by default. On MacOS, due to the system protection mechanism, OpenD.app will be assigned a random path at run time, so that the original path can not be found. At this point, there are the following methods:
    - Execute fixrun.sh under tar package
    - Specify the configuration file path with the command line parameter `-cfg_file`, as described below

* The log level defaults to the info level. During the system development phase, it is not recommended to close the log or modify the log to the warning, error, fatal level to prevent failure to locate problems.
:::

### Step 4: Login
* Enter your account number and password to login.  
You need to complete the questionnaire evaluation and agreement confirmation when you log in for the first time.  
You can see your account information and [quote right](../intro/authority.md#5331), After logging in successfully.

---

# Environment Setup

::: tip Notice
Ways of building programming environment are different for different programming languages.
:::


## Python Environment
### Environment Requirement
* Operating system requirements:  
    * 32-bit or 64-bit operating system of Windows 7/10   
    * 64-bit operating system of Mac 10.11 and above   
    * 64-bit operating system of CentOS 7 and above   
    * 64-bit operating system of Ubuntu 16.04 and above  
* Python version requirements:   
    * Python 3.6 or above


### Environment Building
#### 1. Install Python

To avoid running failures due to environmental problems, we recommend Python version 3.8.

Download page: [Download Python](https://www.python.org/downloads/)

::: details Tips
Two methods are provided to switch to a Python 3.8 environment:
* Method 1  
Add the installation path of Python 3.8 to the environment variable path.

* Method 2  
If you are using PyCharm, you can switch the Project Interpreter to specified Python environment in *Settings*.

![pycharm-switch-python](../img/pycharm-switch-python.png)

:::

After the installation, execute the following command to see if the installation is successful:  
`python -V` (Windows) or `python3 -V` (Linux/Mac)

#### 2. Install PyCharm (Optional)

We recommend that using [PyCharm](https://www.jetbrains.com/pycharm/download/) as your Python IDE.

#### 3. Install TA-Lib (Optional)
TA-Lib is a functional library widely used in program trading for technical analysis of market data. It provides a variety of technical analysis functions to facilitate our quantitative investment.

Installation method: directly use pip installation in cmd  
`$ pip install TA-Lib`

::: tip 提示
* Installation of TA-Lib is not necessary, you can skip this step
:::

---

# Program Samples

## Python Example

### Step 1: Download and install OpenD

Please refer to [here](./opend-base.md) to finish downloading, installing and logging in OpenD.

### Step 2: Download Python API

* Method 1: Use pip install in cmd.
  * Initial installation: Windows: `$ pip install moomoo-api`, Linux/Mac `$ pip3 install moomoo-api`.
  * Secondary upgrade: Windows: `$ pip install moomoo-api --upgrade`，Linux/Mac `$ pip3 install moomoo-api --upgrade`.

* Method 2: Download latest version of Python API from [moomoo official website](https://www.moomoo.com/download/OpenAPI). 

### Step 3: Create New Project

Open PyCharm and click 'New Project' from 'Welcome to PyCharm' window. If you have already created a project, you can open the project directly.

![demo-newproject](../img/demo-newproject.png)

### Step 4: Create new file

Create new Python file under the project, and copy the sample code below to that file.
The sample code includes viewing the market snapshot and placing an order through paper trading account.

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)  # Create quote object
print(quote_ctx.get_market_snapshot('HK.00700'))  # Get market snapshot for HK.00700
quote_ctx.close() # Close object to prevent the number of connextions from running out


trd_ctx = OpenSecTradeContext(host='127.0.0.1', port=11111)  # Create trade object
print(trd_ctx.place_order(price=500.0, qty=100, code="HK.00700", trd_side=TrdSide.BUY, trd_env=TrdEnv.SIMULATE))  # Placing an order through paper trading account (It is nessary to unlock trade by trading password for placing orders in the real environment.)

trd_ctx.close()  # Close object to prevent the number of connextions from running out
```


### Step 5: Running file

Run the project, and you can see the returned message of a successful run as follows:

```
2020-11-05 17:09:29,705 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;
2020-11-05 17:09:29,705 [open_context_base.py] on_connected:344: Connected : conn_id=1; 
2020-11-05 17:09:29,706 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=1; info={'server_version': 218, 'login_user_id': 7157878, 'conn_id': 6730043337026687703, 'conn_key': '3F17CF3EEF912C92', 'conn_iv': 'C119DDDD6314F18A', 'keep_alive_interval': 10, 'is_encrypt': False};
(0,        code          update_time  last_price  open_price  high_price  ...  after_high_price  after_low_price  after_change_val  after_change_rate  after_amplitude
0  HK.00700  2020-11-05 16:08:06       625.0       610.0       625.0  ...               N/A              N/A               N/A                N/A              N/A

[1 rows x 132 columns])
2020-11-05 17:09:29,739 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;
2020-11-05 17:09:29,739 [network_manager.py] work:366: Close: conn_id=1
2020-11-05 17:09:29,739 [open_context_base.py] on_connected:344: Connected : conn_id=2; 
2020-11-05 17:09:29,740 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=2; info={'server_version': 218, 'login_user_id': 7157878, 'conn_id': 6730043337169705045, 'conn_key': 'A624CF3EEF91703C', 'conn_iv': 'BF1FF3806414617B', 'keep_alive_interval': 10, 'is_encrypt': False};
(0,        code stock_name trd_side order_type order_status  ... dealt_avg_price  last_err_msg  remark time_in_force fill_outside_rth
0  HK.00700       腾讯控股      BUY     NORMAL   SUBMITTING  ...             0.0                                 DAY              N/A

[1 rows x 16 columns])
2020-11-05 17:09:32,843 [network_manager.py] work:366: Close: conn_id=2
(0,        code stock_name trd_side      order_type order_status  ... dealt_avg_price  last_err_msg  remark time_in_force fill_outside_rth
0  HK.00700       腾讯控股      BUY  ABSOLUTE_LIMIT    SUBMITTED  ...             0.0                                 DAY              N/A

[1 rows x 16 columns])
```

---

# Strategy Setup

::: tip Tips
* The content of this trading strategy is not an investment advice. It is for learning purposes only.
:::

## Strategy Introduction

Contruct a Double Moving Averaging Strategy. 

That is, using the 1 minute candlestick of an underlying stock, to calculate two moving averages of different periods, MA1 and MA3. The values of MA1 and MA3 are tracked to determine the timing of buying and selling. 

When MA1 >= MA3, the underlying stock is judged to be strong and the market is considered to be a bull market, which shows a long signal.  
When MA1 < MA3, the underlying stock is judged to be weak and the market is considered to be a bear market, which shows a short signal.

## Flow Chart
![strategy-flow-chart](../img/strategy-flow-chart.png)

## Code Sample

* **Example** 

```python
from moomoo import *

############################ Global Variables ############################
MOOMOOOPEND_ADDRESS = '127.0.0.1'  # mooomoo OpenD listening address
MOOMOOOPEND_PORT = 11111  # mooomoo OpenD listening port

TRADING_ENVIRONMENT = TrdEnv.SIMULATE  # Trading environment: REAL / SIMULATE
TRADING_MARKET = TrdMarket.HK  # Transaction market authority, used to filter accounts
TRADING_PWD = '123456'  # Trading password, used to unlock trading for real trading environment
TRADING_PERIOD = KLType.K_1M  # Underlying trading time period
TRADING_SECURITY = 'HK.00700'  # Underlying trading security code
FAST_MOVING_AVERAGE = 1  # Parameter for fast moving average
SLOW_MOVING_AVERAGE = 3  # Parameter for slow moving average

quote_context = OpenQuoteContext(host=MOOMOOOPEND_ADDRESS, port=MOOMOOOPEND_PORT)  # Quotation context
trade_context = OpenSecTradeContext(filter_trdmarket=TRADING_MARKET, host=MOOMOOOPEND_ADDRESS, port=MOOMOOOPEND_PORT, security_firm=SecurityFirm.FUTUSECURITIES)  # Trading context. It must be consistent with the underlying varieties.


# Unlock trade
def unlock_trade():
    if TRADING_ENVIRONMENT == TrdEnv.REAL:
        ret, data = trade_context.unlock_trade(TRADING_PWD)
        if ret != RET_OK:
            print('Unlock trade failed: ', data)
            return False
        print('Unlock Trade success!')
    return True


# Check if it is regular trading time for underlying security
def is_normal_trading_time(code):
    ret, data = quote_context.get_market_state([code])
    if ret != RET_OK:
        print('Get market state failed: ', data)
        return False
    market_state = data['market_state'][0]
    '''
    MarketState.MORNING            HK and A-share morning
    MarketState.AFTERNOON          HK and A-share afternoon, US opening hours
    MarketState.FUTURE_DAY_OPEN    HK, SG, JP futures day market open
    MarketState.FUTURE_OPEN        US futures open
    MarketState.FUTURE_BREAK_OVER  Trading hours of U.S. futures after break
    MarketState.NIGHT_OPEN         HK, SG, JP futures night market open
    '''
    if market_state == MarketState.MORNING or \
                    market_state == MarketState.AFTERNOON or \
                    market_state == MarketState.FUTURE_DAY_OPEN  or \
                    market_state == MarketState.FUTURE_OPEN  or \
                    market_state == MarketState.FUTURE_BREAK_OVER  or \
                    market_state == MarketState.NIGHT_OPEN:
        return True
    print('It is not regular trading hours.')
    return False


# Get positions
def get_holding_position(code):
    holding_position = 0
    ret, data = trade_context.position_list_query(code=code, trd_env=TRADING_ENVIRONMENT)
    if ret != RET_OK:
        print('Get holding position failed：', data)
        return None
    else:
        for qty in data['qty'].values.tolist():
            holding_position += qty
        print('[Holding Position Status] The holding position quantity of {} is：{}'.format(TRADING_SECURITY, holding_position))
    return holding_position


# Query for candlesticks, calculate moving average value and judge bull or bear
def calculate_bull_bear(code, fast_param, slow_param):
    if fast_param <= 0 or slow_param <= 0:
        return 0
    if fast_param > slow_param:
        return calculate_bull_bear(code, slow_param, fast_param)
    ret, data = quote_context.get_cur_kline(code=code, num=slow_param + 1, ktype=TRADING_PERIOD)
    if ret != RET_OK:
        print('Get candlestick value failed: ', data)
        return 0
    candlestick_list = data['close'].values.tolist()[::-1]
    fast_value = None
    slow_value = None
    if len(candlestick_list) > fast_param:
        fast_value = sum(candlestick_list[1: fast_param + 1]) / fast_param
    if len(candlestick_list) > slow_param:
        slow_value = sum(candlestick_list[1: slow_param + 1]) / slow_param
    if fast_value is None or slow_value is None:
        return 0
    return 1 if fast_value >= slow_value else -1


# Get ask1 and bid1 from order book
def get_ask_and_bid(code):
    ret, data = quote_context.get_order_book(code, num=1)
    if ret != RET_OK:
        print('Get order book failed: ', data)
        return None, None
    return data['Ask'][0][0], data['Bid'][0][0]


# Open long positions
def open_position(code):
    # Get order book data
    ask, bid = get_ask_and_bid(code)

    # Get quantity
    open_quantity = calculate_quantity()

    # Check whether buying power is enough
    if is_valid_quantity(TRADING_SECURITY, open_quantity, ask):
        # Place order
        ret, data = trade_context.place_order(price=ask, qty=open_quantity, code=code, trd_side=TrdSide.BUY,
                                              order_type=OrderType.NORMAL, trd_env=TRADING_ENVIRONMENT,
                                              remark='moving_average_strategy')
        if ret != RET_OK:
            print('Open position failed: ', data)
    else:
        print('Maximum quantity that can be bought less than transaction quantity.')


# Close position
def close_position(code, quantity):
    # Get order book data
    ask, bid = get_ask_and_bid(code)

    # Check quantity
    if quantity == 0:
        print('Invalid order quantity.')
        return False

    # Close position
    ret, data = trade_context.place_order(price=bid, qty=quantity, code=code, trd_side=TrdSide.SELL,
                   order_type=OrderType.NORMAL, trd_env=TRADING_ENVIRONMENT, remark='moving_average_strategy')
    if ret != RET_OK:
        print('Close position failed: ', data)
        return False
    return True


# Calculate order quantity
def calculate_quantity():
    price_quantity = 0
    # Use minimum lot size
    ret, data = quote_context.get_market_snapshot([TRADING_SECURITY])
    if ret != RET_OK:
        print('Get market snapshot failed: ', data)
        return price_quantity
    price_quantity = data['lot_size'][0]
    return price_quantity


# Check the buying power is enough for the quantity
def is_valid_quantity(code, quantity, price):
    ret, data = trade_context.acctradinginfo_query(order_type=OrderType.NORMAL, code=code, price=price,
                                                   trd_env=TRADING_ENVIRONMENT)
    if ret != RET_OK:
        print('Get max long/short quantity failed: ', data)
        return False
    max_can_buy = data['max_cash_buy'][0]
    max_can_sell = data['max_sell_short'][0]
    if quantity > 0:
        return quantity < max_can_buy
    elif quantity < 0:
        return abs(quantity) < max_can_sell
    else:
        return False


# Show order status
def show_order_status(data):
    order_status = data['order_status'][0]
    order_info = dict()
    order_info['Code'] = data['code'][0]
    order_info['Price'] = data['price'][0]
    order_info['TradeSide'] = data['trd_side'][0]
    order_info['Quantity'] = data['qty'][0]
    print('[OrderStatus]', order_status, order_info)


############################ Fill in the functions below to finish your trading strategy ############################
# Strategy initialization. Run once when the strategy starts
def on_init():
    # unlock trade (no need to unlock for paper trading)
    if not unlock_trade():
        return False
    print('************  Strategy Starts ***********')
    return True


# Run once for each tick. You can write the main logic of the strategy here
def on_tick():
    pass


# Run once for each new candlestick. You can write the main logic of the strategy here
def on_bar_open():
    # Print seperate line
    print('*****************************************')

    # Only trade during regular trading hours
    if not is_normal_trading_time(TRADING_SECURITY):
        return

    # Query for candlesticks, and calculate moving average value
    bull_or_bear = calculate_bull_bear(TRADING_SECURITY, FAST_MOVING_AVERAGE, SLOW_MOVING_AVERAGE)

    # Get positions
    holding_position = get_holding_position(TRADING_SECURITY)

    # Trading signals
    if holding_position == 0:
        if bull_or_bear == 1:
            print('[Signal] Long signal. Open long positions.')
            open_position(TRADING_SECURITY)
        else:
            print('[Signal] Short signal. Do not open short positions.')
    elif holding_position > 0:
        if bull_or_bear == -1:
            print('[Signal] Short signal. Close positions.')
            close_position(TRADING_SECURITY, holding_position)
        else:
            print('[Signal] Long signal. Do not add positions.')


# Run once when an order is filled
def on_fill(data):
    pass


# Run once when the status of an order changes
def on_order_status(data):
    if data['code'][0] == TRADING_SECURITY:
        show_order_status(data)


############################### Framework code, which can be ignored ###############################
class OnTickClass(TickerHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        on_tick()


class OnBarClass(CurKlineHandlerBase):
    last_time = None
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(OnBarClass, self).on_recv_rsp(rsp_pb)
        if ret_code == RET_OK:
            cur_time = data['time_key'][0]
            if cur_time != self.last_time and data['k_type'][0] == TRADING_PERIOD:
                if self.last_time is not None:
                    on_bar_open()
                self.last_time = cur_time


class OnOrderClass(TradeOrderHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret, data = super(OnOrderClass, self).on_recv_rsp(rsp_pb)
        if ret == RET_OK:
            on_order_status( data)


class OnFillClass(TradeDealHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret, data = super(OnFillClass, self).on_recv_rsp(rsp_pb)
        if ret == RET_OK:
            on_fill(data)


# Main function
if __name__ == '__main__':
    # Strategy initialization
    if not on_init():
        print('Strategy initialization failed, exit script!')
        quote_context.close()
        trade_context.close()
    else:
        # Set up callback functions
        quote_context.set_handler(OnTickClass())
        quote_context.set_handler(OnBarClass())
        trade_context.set_handler(OnOrderClass())
        trade_context.set_handler(OnFillClass())

        # Subscribe tick-by-tick, candlestick and order book of the underlying trading security
        quote_context.subscribe(code_list=[TRADING_SECURITY], subtype_list=[SubType.TICKER, SubType.ORDER_BOOK, TRADING_PERIOD])

```

* **Output**

```
************  Strategy Starts ***********
*****************************************
[Position] The position of HK.00700 is 0
[Signal] Long signal. Open long positions.
[OrderStatus] SUBMITTING {'Code': 'HK.00700', 'Price': 597.5, 'TradeSide': 'BUY', 'Quantity': 100.0}
[OrderStatus] SUBMITTED {'Code': 'HK.00700', 'Price': 597.5, 'TradeSide': 'BUY', 'Quantity': 100.0}
[OrderStatus] FILLED_ALL {'Code': 'HK.00700', 'Price': 597.5, 'TradeSide': 'BUY', 'Quantity': 100.0}
*****************************************
[Position] The position of HK.00700 is 100.0
[Signal] Short signal. Close positions.
[OrderStatus] SUBMITTING {'Code': 'HK.00700', 'Price': 596.5, 'TradeSide': 'SELL', 'Quantity': 100.0}
[OrderStatus] SUBMITTED {'Code': 'HK.00700', 'Price': 596.5, 'TradeSide': 'SELL', 'Quantity': 100.0}
[OrderStatus] FILLED_ALL {'Code': 'HK.00700', 'Price': 596.5, 'TradeSide': 'SELL', 'Quantity': 100.0}
```

---

# Overview

* OpenD, which can be runned on your local computer or cloud server, is the gateway program of moomoo API. It is responsible for transferring protocol requests to moomoo servers and returning the processed data. It is a necessary prerequisite for running moomoo API programs.
* OpenD can be runned under 4 operating systems: Windows, MacOS, CentOS and Ubuntu.

* You need to log in to OpenD with your *moomoo ID*, *Email*, *Phone number* and *login password*.

* After a successful login into OpenD, the socket service is started for moomoo API to connect and communicate.

## Install OpenD

There are 2 modes to run OpenD, you can choose 1 of them below:
* Visualisation OpenD: Provide interface applications, easy to operate, especially suitable for beginners. Please refer to [Visualization OpenD](../quick/opend-base.md) for installation and operation.
* Command Line OpenD: Provide command line execution program, which needs to be configured by yourself, which is suitable for users who are familiar with the command line or running on the server for a long time. Please refer to [Command Line OpenD](../opend/opend-cmd.md) for installation and operation.

## Operation While Running

While OpenD is running, you can view user quota, quote right, connection status, delay statistics, and operate closing API connection, re-login, logging out etc. with Operation Command.  
For more information, please see the following table: 

 Method | Visualisation OpenD | Command Line OpenD
:-|:-|:-
Direct Method | through the UI interface | Send [Operation Command](../opend/opend-operate.md) through command line
Indirect Medhod | Send [Operation Command](../opend/opend-operate.md) through Telnet | Send [Operation Command](../opend/opend-operate.md) through Telnet

---

# Command Line OpenD

### Step 1: Download

* You can download through [moomoo official website](https://www.moomoo.com/download/OpenAPI).

![download-page](../img/mmdownload-page.png)
### Step 2: Decompression
* Extract the file downloaded in the previous step and find the OpenD configuration file OpenD.xml and the program packaged data file Appdata.dat in the folder.
    * OpenD.xml is used to configure the startup parameters of the OpenD program. If it does not exist, the program cannot start correctly.
    * Appdata.dat is a large amount of data information the program needs to use, packaging data to reduce the time of downloading data while starting OpenD. If it does not exist, the program can not start correctly.
* Command line OpenD supports user-defined file paths, refer to [Command line startup parameters](../opend/opend-cmd.md#7191)。

### Step 3: Parameter Configuration
* Open and edit the configuration file OpenD.xml as the picture below. For general use, you only need to change your account and login password, and other options can be modified according to the instructions in the following table.

![xml-config](../img/mmxml.png)

**Configuration item list**：

Configuration Item |Description
:-|:-
ip|listening address.  (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards)
  - the address of one of your network card 127.0.0.1 by default.)
api_port|API protocol receiving port.  (11111 by default.
Also can be specified in [Command Line Startup](./opend-cmd.md#7191).)
login_account|Login account.  (Support UserID, Email, Phone, can be specified in [Command Line Startup](./opend-cmd.md#7191).

  - UserID: moomoo ID
  - Email: xxxx@xx.com 
  - Phone: Area code+number, e.g.,+1 xxxxxxxx)
login_pwd|Login password in plaintext.  (- Also can be specified with login password ciphertext
  - Also can be specified in [Command Line Startup](./opend-cmd.md#7191).)
login_pwd_md5|Login password ciphertext (32-bit MD5 encrypted hexadecimal).  (- When both ciphertext and plaintext exist, only ciphertext is used.
  - Also can be specified with login password plaintext.)
Lang|Language. (Option:

  - Simplified Chinese
  - English)
log_level|Log level of OpenD.  (Option: 

  - no (no log) 
  - debug (the most detailed)
  - info (less detailed)*info* level by default.)
push_proto_type|API protocol type.  (Determines the format of the package body. Option: 
  - 0 (pb) 
  - 1 (json)PB format by default)
qot_push_frequency|API subscription data push frequency  (- In milliseconds.
  - Candlestick and Time Frame are not included.
  - If not set, the frequency will not be limited.)
telnet_ip|Remote operation command listening address.  (127.0.0.1 by default.)
telnet_port|Remote operation command listening port.  (If not set, remote command will not be enabled.)
rsa_private_key|API protocol [RSA](../qa/other.md#1479) encrypted private key (PKCS#1) file absolute path. (If not set, the protocol will not be encrypted.)
price_reminder_push|Whether to receive the price reminder.  (Option: 
  - 0: not received, 
  - 1: received (callback function [set_handler](/en/ftapi/init.html#8418) needs to be set in the script).It will be pushed by default.)
auto_hold_quote_right|Whether to automatically grab quote right after being kicked.  (Option: 
  - 0: No, 
  - 1: Yes (when this option is enabled, FutuOpenD will automatically grab back quote right after being grabbed. If it is robbed again within 10 seconds, the other terminal will get the highest quote right, and FutuOpenD will not grab it again).The permission will be robbed automatically by default.)
future_trade_api_time_zone|Specify the futures trading API time zone.  (- When trading API is called with futures accounts, the time involved is in accordance with this parameter. 
  -  Also can be specified in [Command Line Startup](./opend-cmd.md#7191). 
  - If not set, the exchange time zone will be the default.)
websocket_ip|WebSocket listening address.  (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards)127.0.0.1 by default.)
websocket_port|WebSocket service listening port.  (If not set, WebSocket service will not be enabled.)
websocket_key_md5|Key ciphertext (32-bit MD5 encrypted hexadecimal).  (Used to judge whether the connection is trusted when JavaScript scripts are connected.)
websocket_private_key|WebSocket certificate private key file path.  (- The private key cannot be configured with a password.  
  - If not configured, WebSocket is not enabled.  
  - It needs to be configured at the same time with the certificate.)
websocket_cert|WebSocket certificate file path.  (- If not configured, WebSocket is not enabled.
  -  It needs to be configured with the private key at the same time.) 
pdt_protection|Whether to turn on the Pattern Day Trade Protection.  (**Specific parameters for FUTU US**Option: 
  - 0: No, 
  - 1: Yes (We will prevent you from placing orders which might mark you as a Pattern Day Trader(PDT). The Protection can not guarentee that you won't be marked as a PDT. If you are marked as a PDT, you will not be allowed to open new positions until your equity is above $25000.)The Pattern Day Trade Protection will be turned on by default.)
dtcall_confirmation|Whether to turn on the Day-Trading Call Warning.  (**Specific parameters for FUTU US**Option: 
  - 0: No, 
  - 1: Yes (We will prevent you from placing orders which might exceed your remaining day-trading buying power. We will alert you that you are placing orders that exceed your remaining day-trading buying power. If you close the positions today, you will receive a Day-Trading Call. The DT Call can ONLY be met by depositing funds in the full amount of the call.)The Day-Trading Call Warning will be turned on by default.)


:::tip Tips
* To ensure safety of your trading accounts, if the listening address is not local, you must configure a private key to use the trading interface. The quote interface is not subject to this restriction.
* When the WebSocket listening address is not local, you need to configure SSL to start it, and a password should not be set during the certificate private key generation.
* Ciphertext is represented in hexadecimal after plaintext is encrypted by 32-bit MD5, which can be calculated by searching online MD5 encryption (note that there may be a risk of records colliding with libraries calculated through third-party websites) or by downloading MD5 computing tools. The 32-bit MD5 ciphertext is shown in the red box area (e10adc3949ba59abbe56e057f20f883e):

  ![md5.png](../img/md5.png)

* OpenD reads OpenD.xml in the same directory by default. On MacOS, due to the system protection mechanism, OpenD.app will be assigned a random path at run time, so that the original path can not be found. At this point, there are the following methods:
    - Execute fixrun.sh under tar package
    - Specify the configuration file path with the command line parameter `-cfg_file`, as described below
* The log level defaults to the info level. During the system development phase, it is not recommended to close the log or modify the log to the warning, error, fatal level to prevent failure to locate problems.
:::

### Step 4: Command Line Startup
* On the command line, change the directory to the folder which OpenD is located, and run the following command to start Command Line OpenD with configuration from OpenD.xml.
    * Windows：`OpenD`  
    * Linux：`./OpenD`  
    * MacOS：`./OpenD.app/Contents/MacOS/OpenD`  
::: details Command Line Startup Parameters
* You can also start with parameters on the command line, some of which are the same as the OpenD.xml configuration file. Parameter format: `-key=value`
![startup-command-param.png](../img/startup-command-param.png)   
For example:   
    * Windows：`OpenD.exe -login_account=100000 -login_pwd=123456 -lang=en`  
    * Linux：`OpenD -login_account=100000 -login_pwd=123456 -lang=en`  
    * MacOS：`./OpenD.app/Contents/MacOS/OpenD -login_account=100000 -login_pwd=123456 -lang=en`

:::

* If the same parameters exist on both the command line and the configuration file, the command line parameters take precedence. For details of the parameters, please see the following table:

**parameter list**:

Configuration Item|Description
:-|:-
login_account|Login account. (Also can be specified in configuration file.)
login_pwd|Plaintext of login password. (Also can be specified in configuration file.)
login_pwd_md5|Login password ciphertext (32-bit MD5 encrypted hexadecimal). (- When both ciphertext and plaintext exist, only ciphertext is used. 
  - Also can be specified in configuration file.) 
cfg_file|The absolute path of OpenD configuration file. (If not set, use  __*OpenD.xml*__  in the directory where the program is located.)
console|Whether to display the console.  (Option: 

  - 0: background operation 
  - 1: console operation Console operation by default.)
lang|OpenD language (Option:

  - Simplified Chinese
  - English) 
api_ip|API service listening address. (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards)
  - the address of one of your network card)
api_port|API listening port.
help|Output startup command line parameters and exit the program.
log_level|Log level of OpenD. (Option: 

  - no (no log) 
  - debug (the most detailed)
  - info (less detailed))
no_monitor|Whether to start the daemon.  (Option:

  - 0: start
  - 1: do not startStart with the daemon by default.) 
websocket_ip|WebSocket listening address. (Option: 

  - 127.0.0.1 (for local connections) 
  - 0.0.0.0 (for connections from all network cards))
websocket_port|WebSocket service listening port.
websocket_private_key|WebSocket certificate private key file path.  (- The private key cannot be configured with a password.  
  - If not configured, WebSocket is not enabled.  
  - It needs to be configured at the same time with the certificate.)
websocket_cert|WebSocket certificate file path. (- If not configured, WebSocket is not enabled.
  -  It needs to be configured with the private key at the same time.) 
websocket_key_md5|Key ciphertext (32-bit MD5 encrypted hexadecimal).  (Used to judge whether the connection is trusted when JavaScript scripts are connected.)
price_reminder_push|Whether to receive the price reminder. (Option: 
  - 0: not received, 
  - 1: received (callback function [set_handler](/en/ftapi/init.html#8418) needs to be set in the script).It will be pushed by default.)
auto_hold_quote_right|Whether to automatically grab quote right after being kicked. (Option: 
  - 0: No, 
  - 1: Yes (when this option is enabled, OpenD will automatically grab back quote right after being grabbed. If it is robbed again within 10 seconds, the other terminal will get the highest quote right, and OpenD will not grab it again).The permission will be robbed automatically by default.)
future_trade_api_time_zone|Specify the futures *Trade API* time zone.  (- When *Trade API* is called with futures accounts, the time involved is in accordance with this parameter. 
  -  Also can be specified in configuration file.)


:::

---

# Operation Command

You can do operate OpenD by sending Operation Command from the command line or Telent.

Command format: `cmd -param_key1=param_value1 -param_key2=param_value2`  
Using the following example to describe how to use Telnet: `help -cmd=exit`
1. Configure Telnet address and Telnet port in the OpenD set up parameter.
![telnet_GUI](../img/telnet_GUI.png)
![telnet_CMD](../img/telnet_CMD.jpg)
2. Start OpenD (it will also start Telnet).
3. Via Telnet，send the command `help -cmd=exit` to OpenD。
```python
from telnetlib import Telnet
with Telnet('127.0.0.1', 22222) as tn:  # Telnet address is: 127.0.0.1, Telnet port is: 22222
    tn.write(b'help -cmd=exit\r\n')
    reply = b''
    while True:
        msg = tn.read_until(b'\r\n', timeout=0.5)
        reply += msg
        if msg == b'':
            break
    print(reply.decode('gb2312'))
```

### Command Help
`help -cmd=exit`

View the detailed information of the specified command, output the command list if no parameter is specified

* Parameters:
     - cmd: command

### Exit the Program
`Exit`

Exit OpenD

### Request Mobile Phone Verification Code
`req_phone_verify_code`

Requested mobile phone verification code. Security verification is required when the device lock is enabled and the device is logged in at the first time.

* Frequency limitations:	
  - Maximal 1 request every 60 seconds

### Enter the Phone Verification Code
`Input_phone_verify_code -code=123456`

Enter the phone verification code and continue the login process.

* Parameters:
   - code: mobile phone verification code

* Frequency limitations:	
  - Maximal 10 requests every 60 seconds
 
### Request Graphic Verification Code
`req_pic_verify_code`

Request a graphic verification code. When you enter the wrong login password multiple times, you need to enter the graphic verification code.

* Frequency limitations:	
  - Maximal 10 requests every 60 seconds
  
### Enter Graphic Verification Code
`Input_pic_verify_code -code=1234`

Enter the graphic verification code and continue the login process.

* Parameters:
   - code: Graphic verification code

* Frequency limitations:	
  - Maximal 10 requests every 60 seconds
  
### Relogin
`relogin -login_pwd=123456`

This command can be used when the user is required to log in again when the login password is changed or the device lock is opened midway. You can only relogin to the current account, and changing accounts is not supported.
The password parameter is mainly used to the situation that  the login password had been modified. If login_pwd is not set, the login password at startup will be used.

* Parameters:
  - login_pwd: login password in plaintext
  
  - login_pwd_md5: login password in ciphertext (32-bit MD5 encrypted hexadecimal)

* Frequency limitations:	
  - Maximal 10 requests every hour
  
### Time Delay Between Detection and Connection Point
`ping`

Delay before detection and connection point

* Frequency limitations:	
  - Maximal 10 requests every 60 seconds

### Display Delay Statistics Report
`show_delay_report -detail_report_path=D:/detail.txt -push_count_type=sr2cs`

Display delay statistics report, including push delay, request delay and order delay. Data is cleaned up at 6:00 Beijing time every day.

* Parameters:
  - detail_report_path: file output path (MAC system only supports absolute path, not relative path), optional parameter, if not specified, output to the console
  
  - push_count_type: the type of push delay (sr2ss, ss2cr, cr2cs, ss2cs, sr2cs), sr2cs by default.
    + sr refers to the server receiving time (currently only HK stocks support this time)
    + ss refers to the server sending time
    + cr refers to OpenD receiving time
    + cs refers to OpenD sending time


### Close API Connection
`close_api_conn -conn_id=123456`

Close an API connection, if not specified, close all connections
  
  * Parameters:
    - conn_id: API connection ID

### Show Subscription Status
`show_sub_info -conn_id=123456 -sub_info_path=D:/detail.txt`

Display the subscription status of a connection, if not specified, display all connections
  
  * Parameters:
    - conn_id: API connection ID
  
    - sub_info_path: file output path (MAC system only supports absolute path, not relative path), optional parameter, if not specified, output to the console
  
### Request the Highest Quotation Permission
`request_highest_quote_right`

When the advanced quotation authority is occupied by other devices (such as desktop/mobile terminal), you can use this command to request the highest quotation authority again (And then, other devices that are logged in will not be able to use advanced quote).

* Frequency limitations:	
  - Maximal 10 requests every 60 seconds

### Update
`update`

Update

---

# Overview

<table>
    <tr>
        <th colspan="2">Module</th>
        <th>Interface Name</th>
        <th>Function Description</th>
    </tr>
    <tr>
        <td rowspan="17">Real-time Data</td>
        <td rowspan="4">Subscription</td>
        <td><a href="./sub.html#5009">subscribe</a></td>
        <td>Subscribe real-time market data</td>
    </tr>
    <tr>
        <td><a href="./sub.html#1052">unsubscribe</a></td>
        <td>Unsubscribe subscriptions</td>
    </tr>
    <tr>
        <td><a href="./sub.html#771">unsubscribe_all</a></td>
        <td>Unsubscribe all subscriptions</td>
    </tr>
    <tr>
        <td><a href="./query-subscription.html">query_subscription</a></td>
        <td>Get subscription information</td>
    </tr>
    <tr>
        <td rowspan="6">Push and Callback</td>
        <td><a href="./update-stock-quote.html">StockQuoteHandlerBase</a></td>
        <td>Real-time quote callback</td>
    </tr>
    <tr>
        <td><a href="./update-order-book.html">OrderBookHandlerBase</a></td>
        <td>Real-time order book callback</td>
    </tr>
    <tr>
        <td><a href="./update-kl.html">CurKlineHandlerBase</a></td>
        <td>Real-time candlestick callback</td>
    </tr>
    <tr>
        <td><a href="./update-ticker.html">TickerHandlerBase</a></td>
        <td>Real-time tick-by-tick callback</td>
    </tr>
    <tr>
        <td><a href="./update-rt.html">RTDataHandlerBase</a></td>
        <td>Real-time time frame callback</td>
    </tr>
    <tr>
        <td><a href="./update-broker.html">BrokerHandlerBase</a></td>
        <td>Real-time broker queue callback</td>
    </tr>
    <tr>
        <td rowspan="7">Get</td>
        <td><a href="./get-market-snapshot.html">get_market_snapshot</a></td>
        <td>Get market snapshot</td>
    </tr>
    <tr>
        <td><a href="./get-stock-quote.html">get_stock_quote</a></td>
        <td>Get real-time quote</td>
    </tr>
    <tr>
        <td><a href="./get-order-book.html">get_order_book</a></td>
        <td>Get real-time order book</td>
    </tr>
    <tr>
        <td><a href="./get-kl.html">get_cur_kline</a></td>
        <td>Get real-time candlestick</td>
    </tr>
    <tr>
        <td><a href="./get-rt.html">get_rt_data</a></td>
        <td>Get real-time time frame data</td>
    </tr>
    <tr>
        <td><a href="./get-ticker.html">get_rt_ticker</a></td>
        <td>Get real-time tick-by-tick</td>
    </tr>
    <tr>
        <td><a href="./get-broker.html">get_broker_queue</a></td>
        <td>Get real-time broker queue</td>
    </tr>
    <tr>
        <td rowspan="31" colspan="2">Basic Data</td>
        <td><a href="./get-market-state.html">get_market_state</a></td>
        <td>Get market status of securities</td>
    </tr>
    <tr>
        <td><a href="./get-capital-flow.html">get_capital_flow</a></td>
        <td>Get capital flow</td>
    </tr>
    <tr>
        <td><a href="./get-capital-distribution.html">get_capital_distribution</a></td>
        <td>Get capital distribution</td>
    </tr>
    <tr>
        <td><a href="./get-owner-plate.html">get_owner_plate</a></td>
        <td>Get the stock ownership plate</td>
    </tr>
    <tr>
        <td><a href="./request-history-kline.html">request_history_kline</a></td>
        <td>Get historical candlesticks</td>
    </tr>
    <tr>
        <td><a href="./get-rehab.html">get_rehab</a></td>
        <td>Get the stock adjustment factor</td>
    </tr>
    <tr>
        <td><a href="./get-financials-earnings-price-move.html">get_financials_earnings_price_move</a></td>
        <td>Get Earnings Price Move</td>
    </tr>
    <tr>
        <td><a href="./get-financials-earnings-price-history.html">get_financials_earnings_price_history</a></td>
        <td>Get Earnings Price History</td>
    </tr>
    <tr>
        <td><a href="./get-financials-statements.html">get_financials_statements</a></td>
        <td>Get Financial Statements</td>
    </tr>
    <tr>
        <td><a href="./get-financials-revenue-breakdown.html">get_financials_revenue_breakdown</a></td>
        <td>Get Revenue Breakdown</td>
    </tr>
    <tr>
        <td><a href="./get-research-analyst-consensus.html">get_research_analyst_consensus</a></td>
        <td>Get Research Analyst Consensus</td>
    </tr>
    <tr>
        <td><a href="./get-research-rating-summary.html">get_research_rating_summary</a></td>
        <td>Get Research Rating Summary</td>
    </tr>
    <tr>
        <td><a href="./get-research-morningstar-report.html">get_research_morningstar_report</a></td>
        <td>Get Morningstar Research Report</td>
    </tr>
    <tr>
        <td><a href="./get-valuation-detail.html">get_valuation_detail</a></td>
        <td>Get Valuation Detail</td>
    </tr>
    <tr>
        <td><a href="./get-valuation-plate-stock-list.html">get_valuation_plate_stock_list</a></td>
        <td>Get Valuation Plate Stock List</td>
    </tr>
    <tr>
        <td><a href="./get-corporate-actions-dividends.html">get_corporate_actions_dividends</a></td>
        <td>Get Corporate Actions - Dividends</td>
    </tr>
    <tr>
        <td><a href="./get-corporate-actions-buybacks.html">get_corporate_actions_buybacks</a></td>
        <td>Get Corporate Actions - Buybacks</td>
    </tr>
    <tr>
        <td><a href="./get-corporate-actions-stock-splits.html">get_corporate_actions_stock_splits</a></td>
        <td>Get Corporate Actions - Stock Splits</td>
    </tr>
    <tr>
        <td><a href="./get-shareholders-overview.html">get_shareholders_overview</a></td>
        <td>Get Shareholders Overview</td>
    </tr>
    <tr>
        <td><a href="./get-shareholders-holding-changes.html">get_shareholders_holding_changes</a></td>
        <td>Get Shareholders Holding Changes</td>
    </tr>
    <tr>
        <td><a href="./get-shareholders-holder-detail.html">get_shareholders_holder_detail</a></td>
        <td>Get Shareholders Holder Detail</td>
    </tr>
    <tr>
        <td><a href="./get-shareholders-institutional.html">get_shareholders_institutional</a></td>
        <td>Get Institutional Holdings</td>
    </tr>
    <tr>
        <td><a href="./get-insider-holder-list.html">get_insider_holder_list</a></td>
        <td>Get Insider Holder List</td>
    </tr>
    <tr>
        <td><a href="./get-insider-trade-list.html">get_insider_trade_list</a></td>
        <td>Get Insider Trade List</td>
    </tr>
    <tr>
        <td><a href="./get-company-profile.html">get_company_profile</a></td>
        <td>Get Company Profile</td>
    </tr>
    <tr>
        <td><a href="./get-company-executives.html">get_company_executives</a></td>
        <td>Get Company Executives</td>
    </tr>
    <tr>
        <td><a href="./get-company-executive-background.html">get_company_executive_background</a></td>
        <td>Get Company Executive Background</td>
    </tr>
    <tr>
        <td><a href="./get-company-operational-efficiency.html">get_company_operational_efficiency</a></td>
        <td>Get Company Operational Efficiency</td>
    </tr>
    <tr>
        <td><a href="./get-top-ten-buy-sell-brokers.html">get_top_ten_buy_sell_brokers</a></td>
        <td>Get Top Ten Buy/Sell Brokers</td>
    </tr>
    <tr>
        <td><a href="./get-daily-short-volume.html">get_daily_short_volume</a></td>
        <td>Get Daily Short Volume</td>
    </tr>
    <tr>
        <td><a href="./get-short-interest.html">get_short_interest</a></td>
        <td>Get Short Interest</td>
    </tr>
    
    <tr>
        <td rowspan="27" colspan="2">Related Derivatives</td>
        <td><a href="../quote/get-option-expiration-date.html">get_option_expiration_date</a></td>
        <td>Query all expiration dates of option chains through the underlying stock.</td>
    </tr>
    <tr>
        <td><a href="./get-option-chain.html">get_option_chain</a></td>
        <td>Get the option chain from an underlying stock</td>
    </tr>
    <tr>
        <td><a href="./get-option-screen.html">get_option_screen</a></td>
        <td>Option screener supporting hybrid filtering on underlying and option attributes</td>
    </tr>
    <tr>
        <td><a href="./get-warrant.html">get_warrant</a></td>
	    <td>Get filtered warrant (for HK market only)</td>
    </tr>
    <tr>
        <td><a href="./get-warrant-screen.html">get_warrant_screen</a></td>
        <td>Warrant screener V2, returning 45 warrant attributes</td>
    </tr>
    <tr>
        <td><a href="./get-referencestock-list.html">get_referencestock_list</a></td>
        <td>Get related data of securities</td>
    </tr>
    <tr>
        <td><a href="./get-future-info.html">get_future_info</a></td>
        <td>Get futures contract information</td>
    </tr>
    <tr>
        <td><a href="./get-option-volatility.html">get_option_volatility</a></td>
        <td>Get Option Volatility</td>
    </tr>
    <tr>
        <td><a href="./get-option-exercise-probability.html">get_option_exercise_probability</a></td>
        <td>Get Option Exercise Probability</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-strategy.html">get_option_strategy</a></td>
	    <td>Get Option Strategy</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-strategy-spread.html">get_option_strategy_spread</a></td>
	    <td>Get Valid Spread</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-strategy-analysis.html">get_option_strategy_analysis</a></td>
	    <td>Option Strategy Analysis</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-quote.html">get_option_quote</a></td>
	    <td>Get Option Quote</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-market-statistic.html">get_option_market_statistic</a></td>
	    <td>Option Market Statistics</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-underlying-overview.html">get_option_underlying_overview</a></td>
	    <td>Option Underlying Overview</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-underlying-his-statistic.html">get_option_underlying_his_statistic</a></td>
	    <td>Option Underlying Historical Statistics</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-underlying-his-volatility.html">get_option_underlying_his_volatility</a></td>
	    <td>Option Underlying Historical Volatility</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-underlying-rank.html">get_option_underlying_rank</a></td>
	    <td>Option Underlying Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-rank.html">get_option_rank</a></td>
	    <td>Option Contract Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-event.html">get_option_event</a></td>
	    <td>Option Unusual Activity</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-event-alert.html">get_option_event_alert</a></td>
	    <td>Get Option Event Alert</td>
    </tr>
    <tr>
	    <td><a href="../quote/set-option-event-alert.html">set_option_event_alert</a></td>
	    <td>Set Option Event Alert</td>
    </tr>
    <tr>
	    <td><a href="../quote/update-option-event.html">OptionEventHandlerBase</a></td>
	    <td>Option Event Push</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-zero-dte-screener.html">get_option_zero_dte_screener</a></td>
	    <td>Zero DTE Option Screener</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-zero-dte-contract.html">get_option_zero_dte_contract</a></td>
	    <td>Zero DTE Option Contracts</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-earnings-screener.html">get_option_earnings_screener</a></td>
	    <td>Option Earnings Screener</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-option-seller-screener.html">get_option_seller_screener</a></td>
	    <td>Option Seller Screener</td>
    </tr>
    <tr>
        <td rowspan="10" colspan="2">Market Filter</td>
        <td><a href="./get-stock-filter.html">get_stock_filter</a></td>
        <td>Filter stocks by condition</td>
    </tr>
    <tr>
        <td><a href="./get-stock-screen.html">get_stock_screen</a></td>
        <td>Stock screener V2 covering 11 factor groups (244+ factors), with multi-field sorting and explicit retrieval</td>
    </tr>
    <tr>
        <td><a href="./get-plate-stock.html">get_plate_stock</a></td>
        <td>Get the list of stocks in the plate</td>
    </tr>
    <tr>
        <td><a href="./get-plate-list.html">get_plate_list</a></td>
        <td>Get plate list</td>
    </tr>
    <tr>
        <td><a href="./get-static-info.html">get_stock_basicinfo</a></td>
        <td>Get stock basic information</td>
    </tr>
    <tr>
        <td><a href="./get-ipo-list.html">get_ipo_list</a></td>
        <td>Get IPO information of a specific market</td>
    </tr>
    <tr>
        <td><a href="./get-global-state.html">get_global_state</a></td>
        <td>Get global status</td>
    </tr>
    <tr>
        <td><a href="./request-trading-days.html">request_trading_days</a></td>
        <td>Get trading calendar</td>
    </tr>
    <tr>
        <td><a href="./get-search-quote.html">get_search_quote</a></td>
        <td>Search quotes</td>
    </tr>
    <tr>
        <td><a href="./get-search-news.html">get_search_news</a></td>
        <td>Search news</td>
    </tr>
    <tr>
        <td rowspan="33" colspan="2">Market</td>
	    <td><a href="../quote/get-earnings-calendar.html">get_earnings_calendar</a></td>
	    <td>Get Earnings Calendar</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-macro-indicator-list.html">get_macro_indicator_list</a></td>
	    <td>Get Macro Indicator List</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-macro-indicator-history.html">get_macro_indicator_history</a></td>
	    <td>Get macro indicator historical data</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-fed-watch-target-rate.html">get_fed_watch_target_rate</a></td>
	    <td>Get FedWatch target rate probability</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-fed-watch-dot-plot.html">get_fed_watch_dot_plot</a></td>
	    <td>Get FedWatch dot plot</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-earnings-beat-rank.html">get_earnings_beat_rank</a></td>
	    <td>Get Earnings Beat Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-dividend-rank.html">get_dividend_rank</a></td>
	    <td>Get Dividend Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-dividend-calendar.html">get_dividend_calendar</a></td>
	    <td>Get dividend calendar</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-economic-calendar.html">get_economic_calendar</a></td>
	    <td>Get Economic Calendar</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-us-pre-market-rank.html">get_us_pre_market_rank</a></td>
	    <td>Get US Pre-Market Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-us-after-hours-rank.html">get_us_after_hours_rank</a></td>
	    <td>Get US After-Hours Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-us-overnight-rank.html">get_us_overnight_rank</a></td>
	    <td>Get US Overnight Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-top-movers-rank.html">get_top_movers_rank</a></td>
	    <td>Get Top Movers Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-hot-list.html">get_hot_list</a></td>
	    <td>Get Hot List</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-short-selling-rank.html">get_short_selling_rank</a></td>
	    <td>Get Short Selling Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-period-change-rank.html">get_period_change_rank</a></td>
	    <td>Get Period Change Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-high-dividend-soe-rank.html">get_high_dividend_soe_rank</a></td>
	    <td>Get High Dividend SOE Rank</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-institution-list.html">get_institution_list</a></td>
	    <td>Get Institution List</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-institution-profile.html">get_institution_profile</a></td>
	    <td>Get institution overview</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-institution-distribution.html">get_institution_distribution</a></td>
	    <td>Get institution holding industry distribution</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-institution-holding-change.html">get_institution_holding_change</a></td>
	    <td>Get Institution Holding Change</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-institution-holding-list.html">get_institution_holding_list</a></td>
	    <td>Get Institution Holding List</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-ark-fund-holding.html">get_ark_fund_holding</a></td>
	    <td>Get ARK Fund Holding</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-ark-stock-dynamic.html">get_ark_stock_dynamic</a></td>
	    <td>Get ARK stock trading activities</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-ark-active-transaction.html">get_ark_active_transaction</a></td>
	    <td>Get ARK Active Transaction</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-rating-change.html">get_rating_change</a></td>
	    <td>Get Rating Change</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-industrial-chain-list.html">get_industrial_chain_list</a></td>
	    <td>Get industry chain list</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-industrial-chain-detail.html">get_industrial_chain_detail</a></td>
	    <td>Get industry chain details</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-industrial-chain-by-plate.html">get_industrial_chain_by_plate</a></td>
	    <td>Get plate associated industry chains</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-industrial-plate-info.html">get_industrial_plate_info</a></td>
	    <td>Get industry plate information</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-industrial-plate-stock.html">get_industrial_plate_stock</a></td>
	    <td>Get Industrial Plate Stock</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-heat-map-data.html">get_heat_map_data</a></td>
	    <td>Get Heat Map Data</td>
    </tr>
    <tr>
	    <td><a href="../quote/get-rise-fall-distribution.html">get_rise_fall_distribution</a></td>
	    <td>Get Rise/Fall Distribution</td>
    </tr>
    <tr>
        <td rowspan="3" colspan="2">Technical Indicators</td>
        <td><a href="./get-indicator-list.html">get_indicator_list</a></td>
        <td>Get indicator list</td>
    </tr>
    <tr>
        <td><a href="./request-indicator-calc.html">request_indicator_calc_async</a></td>
        <td>Request indicator calculation asynchronously</td>
    </tr>
    <tr>
        <td><a href="./push-indicator-calc.html">IndicatorCalcHandlerBase</a></td>
        <td>Push indicator async calculation result</td>
    </tr>
    <tr>
        <td rowspan="7" colspan="2">Customization</td>
        <td><a href="./get-history-kl-quota.html">get_history_kl_quota</a></td>
        <td>Get usage details of historical candlestick quota</td>
    </tr>
    <tr>
        <td><a href="./set-price-reminder.html">set_price_reminder</a></td>
        <td>Add, delete, modify, enable, and disable price reminders for specified stocks</td>
    </tr>
    <tr>
        <td><a href="./get-price-reminder.html">get_price_reminder</a></td>
        <td>Get a list of price reminders set for the specified stock or market</td>
    </tr>
    <tr>
        <td><a href="./get-user-security-group.html">get_user_security_group</a></td>
        <td>Get a list of groups from the user watchlist</td>
    </tr>
    <tr>
        <td><a href="./get-user-security.html">get_user_security</a></td>
        <td>Get a list of a specified group from watchlist</td>
    </tr>
    <tr>
        <td><a href="./modify-user-security.html">modify_user_security</a></td>
        <td>Modify the specific group from the watchlist</td>
    </tr>
    <tr>
        <td><a href="./update-price-reminder.html">PriceReminderHandlerBase</a></td>
        <td>The price reminder notification callback</td>
    </tr>
</table>

---

# Quote Object

## Create and Initialize the Connection

`OpenQuoteContext(host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)`  

* **Introduction**

     Create and initialize market connection

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    host|str|OpenD listening address.
    port|int|OpenD listening port.
    is_encrypt|bool|Whether to enable encryption.  (- The default is None, which means the setting of [enable_proto_encrypt](../ftapi/init.md#7910) is used. 
  - True: mandatory encryption.False: mandatory no encryption.)
    security_firm|[SecurityFirm](../trade/trade.md#9434)|Security firm  (- Only applicable for creating cryptocurrency quote connections
  - Default value: NONE
  - Only effective when FUTUSECURITIES, FUTUINC, or FUTUSG is passed
  - Passing other firms (MY/AU/JP/CA) or invalid values will result in an error)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111, is_encrypt=False)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

## Close Connection

`close()`

* **Introduction**

Close the interface quotation object. By default, the threads created inside the moomoo API will prevent the process from exiting, and the process can exit normally only after all Contexts are closed. But through [set_all_thread_daemon](../ftapi/init.md#5242), all internal threads can be set as daemon threads. At this time, even if the close of Context is not called, the process can exit normally.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

## Start-up

`start()`

* **Introduction**

     Start to receive push data asynchronously

## Stop

`stop()`

* **Introduction**

     Stop receiving push data asynchronously

---

# Subscribe and Unsubscribe

## subscribe  

`subscribe(code_list, subtype_list, is_first_push=True, subscribe_push=True, is_detailed_orderbook=False, extended_time=False, session=Session.NONE)` 
* **Description**

    To subscribe to the real-time information required for registration, specify the stock and subscription data types.  
    HK market (including underlying stocks, warrants, CBBCs, options, futures) subscriptions require LV1 and above permissions. Subscriptions are not supported under BMP permissions.  
    US market (including underlying stocks, ETFs) subscriptions for overnight quotes require LV1 and above permissions. Subscriptions are not supported under BMP permissions.  

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code_list|list|A list of stock codes that need to be subscribed.  (Data type of elements in the list is str.)
    subtype_list|list|List of data types that need to be subscribed.  (Data type of elements in the list is [SubType](./quote.md#7721).)
    is_first_push|bool|Whether to push the cached data immediately after a successful subscription.  (- True: Push the cached data. When there is a disconnection and reconnection between scripts and OpenD, the last data before the disconnection will be pushed again if it is set to True when resubscribing.
  - False: Do not push the cached data. Wait for the latest data to be pushed from moomoo server.)
    subscribe_push|bool|Whether to push data after subscription. (After subscription, OpenD provides [two methods to obtain data](../qa/quote.html#5505). If you only use the method of **Get Real-time Data** , setting to False can save part of the performance cost.
  - True: Push data. It must be set to True if the **Real-time data Callback** method is used.
  - False: Do not push data. It is recommended to set to False if **only** using the **Get Real-time Data**.)
    is_detailed_orderbook|bool|Whether to subscribe to the detailed order book.  (- Only for Hong Kong stocks ORDER_BOOK type under the authority of Hong Kong stocks SF market. 
  - Under the authority of US stocks & futures LV2, the detailed order book is not provided.)
    extended_time|bool|Whether to allow pre-market and after-hours data of US stocks.  (Only used for subscribing to real-time candlestick and real-time Time Frame and real-time tick-by-tick of US stocks.)
    session|[Session](./quote.md#8688)|US stocks quotes session  (- Only used for subscribing to real-time candlestick and real-time Time Frame and real-time tick-by-tick of US stocks.
  - Please choose 'ALL' to subscribe 24H quotes for US stocks. The 'OVERNIGHT' is not allowed.
  - Minimum version requirements: 9.2.4207)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">err_message</td>
            <td>NoneType</td>
            <td>If ret == RET_OK, None is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>


* **Example**

``` python
import time
from moomoo import *
class OrderBookTest(OrderBookHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(OrderBookTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("OrderBookTest: error, msg: %s"% data)
            return RET_ERROR, data
        print("OrderBookTest ", data) # OrderBookTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = OrderBookTest()
quote_ctx.set_handler(handler) # Set real-time swing callback
quote_ctx.subscribe(['US.AAPL'], [SubType.ORDER_BOOK]) # Subscribe to the order type, OpenD starts to receive continuous push from the server
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

``` python
OrderBookTest  {'code': 'US.AAPL', 'name': 'Apple', 'svr_recv_time_bid': '2025-04-07 05:00:52.266', 'svr_recv_time_ask': '2025-04-07 05:00:53.973', 'Bid': [(180.2, 15, 3, {}), (180.19, 1, 1, {}), (180.18, 11, 2, {}), (180.14, 200, 1, {}), (180.13, 3, 2, {}), (180.1, 99, 3, {}), (180.05, 3, 1, {}), (180.03, 400, 1, {}), (180.02, 10, 1, {}), (180.01, 100, 1, {}), (180.0, 441, 24, {})], 'Ask': [(180.3, 100, 1, {}), (180.38, 4, 2, {}), (180.4, 100, 1, {}), (180.42, 200, 1, {}), (180.46, 29, 1, {}), (180.5, 1019, 2, {}), (180.6, 1000, 1, {}), (180.8, 2001, 3, {}), (180.84, 15, 2, {}), (181.0, 2036, 4, {}), (181.2, 2000, 2, {}), (181.3, 3, 1, {}), (181.4, 2021, 3, {}), (181.5, 59, 2, {}), (181.79, 9, 1, {}), (181.8, 20, 1, {}), (181.9, 94, 4, {}), (181.98, 20, 1, {}), (182.0, 150, 7, {})]}
```

## unsubscribe  

`unsubscribe(code_list, subtype_list, unsubscribe_all=False)`  
* **Description**

    unsubscribe   

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|A list of stock codes to unsubscribe.  (Data type of elements in the list is str.)
    subtype_list|list|List of data types that need to be subscribed.  (Data type of elements in the list is [SubType](./quote.md#7721).)
    unsubscribe_all|bool|Cancel all subscriptions.  (Ignore other parameters when it is True.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">err_message</td>
            <td>NoneType</td>
            <td>If ret == RET_OK, None is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

* **Example**

``` python
from moomoo import *
import time
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

print('current subscription status :', quote_ctx.query_subscription()) # Query the initial subscription status
ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.QUOTE, SubType.TICKER], subscribe_push=False, session=Session.ALL)
# First subscribed to the two types of QUOTE and TICKER. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK: # Subscription successful
    print('subscribe successfully! current subscription status :', quote_ctx.query_subscription()) # Query subscription status after successful subscription
    time.sleep(60) # You can unsubscribe at least 1 minute after subscribing
    ret_unsub, err_message_unsub = quote_ctx.unsubscribe(['US.AAPL'], [SubType.QUOTE])
    if ret_unsub == RET_OK:
        print('unsubscribe successfully! current subscription status:', quote_ctx.query_subscription()) # Query the subscription status after canceling the subscription
    else:
        print('unsubscription failed!', err_message_unsub)
else:
    print('subscription failed', err_message)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

``` python
current subscription status : (0, {'total_used': 0, 'remain': 1000, 'own_used': 0, 'sub_list': {}})
subscribe successfully！current subscription status : (0, {'total_used': 2, 'remain': 998, 'own_used': 2, 'sub_list': {'QUOTE': ['US.AAPL'], 'TICKER': ['US.AAPL']}})
unsubscribe successfully！current subscription status: (0, {'total_used': 1, 'remain': 999, 'own_used': 1, 'sub_list': {'TICKER': ['US.AAPL']}})
```

## unsubscribe_all  

`unsubscribe_all()`  

* **Description**

    Unsubscribe all subscriptions


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">err_message</td>
            <td>NoneType</td>
            <td>If ret == RET_OK, None is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

* **Example** 

``` python
from moomoo import *
import time
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

print('current subscription status :', quote_ctx.query_subscription()) # Query the initial subscription status
ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.QUOTE, SubType.TICKER], subscribe_push=False, session=Session.ALL)
# First subscribed to the two types of QUOTE and TICKER. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK: # Subscription successful
    print('subscribe successfully! current subscription status :', quote_ctx.query_subscription()) # Query subscription status after successful subscription
    time.sleep(60) # You can unsubscribe at least 1 minute after subscribing
    ret_unsub, err_message_unsub = quote_ctx.unsubscribe_all() # Cancel all subscriptions
    if ret_unsub == RET_OK:
        print('unsubscribe all successfully! current subscription status:', quote_ctx.query_subscription()) # Query the subscription status after canceling the subscription
    else:
        print('Failed to cancel all subscriptions！', err_message_unsub)
else:
    print('subscription failed', err_message)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

``` python
current subscription status : (0, {'total_used': 0, 'remain': 1000, 'own_used': 0, 'sub_list': {}})
subscribe successfully！current subscription status : (0, {'total_used': 2, 'remain': 998, 'own_used': 2, 'sub_list': {'QUOTE': ['US.AAPL'], 'TICKER': ['US.AAPL']}})
unsubscribe all successfully！current subscription status: (0, {'total_used': 0, 'remain': 1000, 'own_used': 0, 'sub_list': {}})
```

::: tip Interface Limitations
- Supports subscriptions of multiple real-time data types, refer to [SubType](./quote.md#7721), each stock subscription for one one quota.
- Please refer to [Subscription Quota & Historical Candlestick Quota](../intro/authority.md#9123) for Subscription Quota rules.
- You can unsubscribe after subscribing after at least one minute.
- Due to the large amount of SF market data in Hong Kong stocks, in order to ensure the speed of the SF market and the processing performance of OpenD, currently SF authorized users are restricted to subscribing to the order book and broker queue of only 50 securities products (including hkex stocks, warrants, bulls and bears) at the same time, the remaining subscription quota can still be used to subscribe to other types, such as: tickers and brokerage etc.
- HK options and futures do not support subscription to *TICKER* type under LV1 authority.
:::

---

# Get Subscription Status

`query_subscription(is_all_conn=True)`

* **Description**

    Get subscription information

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    is_all_conn|bool|Whether to return the subscription status of all connections.  (True: return the subscription status of all connections. False: return only the status of the current connection.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, subscription information data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * subscription information data format as follows: 
    
            {
                'total_used': subscription quota used by all connections,
                'own_used': The subscription quota used by the current connection,
                'remain': remaining subscription quota,
                'own_security_firm': 'FUTUSECURITIES',  # Security firm identifier of the current connection
                'sub_list': The stock list corresponding to each subscription type,
                {
                    'Subscription type': A list of all subscribed stocks under this subscription type,
                    …
                }
            }

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE])
ret, data = quote_ctx.query_subscription()
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
{'total_used': 1, 'remain': 999, 'own_used': 1, 'own_security_firm': 'N/A', 'sub_list': {'QUOTE': ['HK.00700']}}
```

---

# Real-time Quote Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time quotation callback, asynchronous processing of real-time quotation push of subscribed stocks.
    After receiving the real-time quote data push, it will call back to this function. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateBasicQot_pb2.Response|This parameter does not need to be processed in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, quotation data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * quotation data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        data_date|str|Date.
        data_time|str|Time of latest price.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        last_price|float|Latest price.
        open_price|float|Open.
        high_price|float|High.
        low_price|float|Low.
        prev_close_price|float|Yesterday's close.
        volume|float|Volume.
        turnover|float|Turnover.
        turnover_rate|float|Turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        amplitude|int|Amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        suspension|bool|Whether trading is suspended.  (True: suspension.)
        listing_date|str|Listing date.  (yyyy-MM-dd)
        price_spread|float|Spread.
        dark_status|[DarkStatus](./quote.md#6341)|Grey market transaction status.
        sec_status|[SecurityStatus](./quote.md#4415)|Stock status.
        strike_price|float|Strike price.
        contract_size|float|Contract size.
        open_interest|int|Number of open positions.
        implied_volatility|float|Implied volatility.  (This field is in percentage form, so 20 is equivalent to 20%.)
        premium|float|Premium.  (This field is in percentage form, so 20 is equivalent to 20%.)
        delta|float|Greek value Delta.
        gamma|float|Greek value Gamma.
        vega|float|Greek value Vega.
        theta|float|Greek value Theta.
        rho|float|Greek value Rho.
        index_option_type|[IndexOptionType](./quote.md#2866)|Index option type.
        net_open_interest|int|Net open contract number.  (Only HK options support this field.)
        expiry_date_distance|int|The number of days from the expiry date.  (A negative number means it has expired.)
        contract_nominal_value|float|Contract nominal amount.  (Only HK options support this field.)
        owner_lot_multiplier|float|Equal number of underlying stocks.  (Index options do not have this field , only HK options support this field.)
        option_area_type|[OptionAreaType](./quote.md#3628)|Option type (by exercise time).
        contract_multiplier|float|Contract multiplier.
        pre_price|float|Pre-market price.
        pre_high_price|float|Pre-market high.
        pre_low_price|float|Pre-market low.
        pre_volume|int|Pre-market volume.
        pre_turnover|float|Pre-market turnover.
        pre_change_val|float|Pre-market change.
        pre_change_rate|float|Pre-market change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        pre_amplitude|float|Pre-market amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_price|float|After-hours price.
        after_high_price|float|After-hours high.
        after_low_price|float|After-hours low.
        after_volume|int|After-hours volume.  (The Sci-tech Innovation Board supports this data.)
        After_turnover|float|After-hours turnover.  (The Sci-tech Innovation Board supports this data.)
        after_change_val|float|After-hours change.
        after_change_rate|float|After-hours change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_amplitude|float|After-hours amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_price|float|Overnight price.
        overnight_high_price|float|Overnight high.
        overnight_low_price|float|Overnight low.
        overnight_volume|int|Overnight volume.
        overnight_turnover|float|Overnight turnover.
        overnight_change_val|float|Overnight change.
        overnight_change_rate|float|Overnight change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_amplitude|float|Overnight amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        last_settle_price|float|Yesterday's close.  (Specific field for futures.)
        position|float|Holding position.  (Specific field for futures.)
        position_change|float|Daily position change.  (Specific field for futures.)

* **Example**

```python
import time
from moomoo import *

class StockQuoteTest(StockQuoteHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(StockQuoteTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("StockQuoteTest: error, msg: %s"% data)
            return RET_ERROR, data
        print("StockQuoteTest ", data) # StockQuoteTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = StockQuoteTest()
quote_ctx.set_handler(handler) # Set real-time quote callback
ret, data = quote_ctx.subscribe(['US.AAPL'], [SubType.QUOTE]) # Subscribe to the real-time quotation type, OpenD starts to continuously receive pushes from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute   	
```

* **Output**

```python
StockQuoteTest        code name data_date data_time  last_price  open_price  high_price  low_price  prev_close_price  volume  turnover  turnover_rate  amplitude  suspension listing_date  price_spread dark_status sec_status strike_price contract_size open_interest implied_volatility premium delta gamma vega theta  rho net_open_interest expiry_date_distance contract_nominal_value owner_lot_multiplier option_area_type contract_multiplier last_settle_price position position_change index_option_type pre_price pre_high_price pre_low_price pre_volume pre_turnover pre_change_val pre_change_rate pre_amplitude after_price after_high_price after_low_price after_volume after_turnover after_change_val after_change_rate after_amplitude overnight_price overnight_high_price overnight_low_price overnight_volume overnight_turnover overnight_change_val overnight_change_rate overnight_amplitude
0  US.AAPL   Apple                             0.0         0.0         0.0        0.0               0.0       0       0.0            0.0        0.0       False                        0.0         N/A     NORMAL          N/A           N/A           N/A                N/A     N/A   N/A   N/A  N/A   N/A  N/A               N/A                  N/A                    N/A                  N/A              N/A                 N/A               N/A      N/A             N/A               N/A       N/A            N/A           N/A        N/A          N/A            N/A             N/A           N/A         N/A              N/A             N/A          N/A            N/A              N/A               N/A             N/A             N/A                  N/A                 N/A              N/A                N/A                  N/A                   N/A                 N/A
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Quote of Securities](./get-ticker.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Real-time Order Book Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time quotation callback, asynchronous processing of real-time quotation push of subscribed stocks.
    It will call back to this function after receiving the push of real-time disk data. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateOrderBook_pb2.Response|This parameter does not need to be processed directly in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, plate data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order Book format as follows：
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        svr_recv_time_bid|str|The time when moomoo server receives order book of bid from the exchange.  (Sometimes the time is zero, e.g. server reboot or first push of cached data.)
        svr_recv_time_ask|str|The time when moomoo server receives order book of ask from the exchange.  (Sometimes the time is zero, e.g. server reboot or first push of cached data.)
        order_book_type|[OrderBookType](./quote.md#9106)|Order book type
        Bid|list|Each tuple contains the following information：Bid price, bid volume, order qty of bid, order details of bid.  (Order details of ask
  - Details: Exchange order ID. Order volume.
  - Up to 1000 order details of ask with HK SF market quotes.  
  - Other quote rights does not support access to such details.)
        Ask|list|Each tuple contains the following information：Ask price, ask volume, order qty of ask, order details of ask.  (Order details of ask
  - Details: Exchange order ID. Order volume.
  - Up to 1000 order details of ask with HK SF market quotes.  
  - Other quote rights does not support access to such details.)

        The format of Bid and Ask fields as follows：  

          'Bid': [ (bid_price1, bid_volume1, order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }), (bid_price2, bid_volume2, order_num,  {'orderid1': order_volume1, 'orderid2': order_volume2, …… }),…]
          'Ask': [ (ask_price1, ask_volume1，order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }), (ask_price2, ask_volume2, order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }),…] 

* **Example**

```python
import time
from moomoo import *
class OrderBookTest(OrderBookHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(OrderBookTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("OrderBookTest: error, msg: %s" % data)
            return RET_ERROR, data
        print("OrderBookTest ", data) # OrderBookTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = OrderBookTest()
quote_ctx.set_handler(handler) # Set real-time swing callback
ret, data = quote_ctx.subscribe(['US.AAPL'], [SubType.ORDER_BOOK]) # Subscribe to the order type, OpenD starts to receive continuous push from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
OrderBookTest  {'code': 'US.AAPL', 'name': 'Apple', 'svr_recv_time_bid': '', 'svr_recv_time_ask': '', 'order_book_type': 'NORMAL', 'Bid': [(179.77, 100, 1, {}), (179.68, 200, 1, {}), (179.65, 2, 2, {}), (179.64, 27, 1, {}), (179.6, 9, 2, {}), (179.58, 39, 2, {}), (179.5, 13, 4, {}), (179.48, 331, 2, {}), (179.4, 1002, 2, {}), (179.38, 330, 1, {}), (179.37, 2, 1, {}), (179.3, 47, 1, {}), (179.28, 330, 1, {}), (179.21, 2, 1, {}), (179.2, 1000, 1, {}), (179.18, 330, 1, {}), (179.17, 100, 1, {}), (179.16, 1, 1, {}), (179.13, 400, 1, {}), (179.1, 3000, 1, {}), (179.08, 330, 1, {}), (179.05, 125, 2, {}), (179.01, 17, 2, {}), (179.0, 81, 7, {})], 'Ask': [(179.95, 400, 2, {}), (180.0, 360, 2, {}), (180.05, 20, 1, {}), (180.1, 246, 4, {}), (180.18, 20, 1, {}), (180.2, 2030, 3, {}), (180.23, 20, 1, {}), (180.3, 23, 1, {}), (180.33, 15, 1, {}), (180.4, 2000, 2, {}), (180.49, 5, 1, {}), (180.59, 253, 1, {}), (180.6, 2000, 2, {}), (180.8, 2010, 3, {}), (181.0, 2018, 4, {}), (181.08, 1, 1, {}), (181.2, 1009, 2, {}), (181.3, 17, 3, {}), (181.4, 1, 1, {}), (181.5, 50, 1, {}), (181.79, 9, 1, {}), (181.9, 66, 2, {})]}
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Orderbook](./get-order-book.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* Real-time order book callback for US stocks, will continuously update data during the current trading session, with no need to set the session parameter.
:::

---

# Real-time Candlestick Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time candlestick callback, asynchronous processing of real-time candlestick push for subscribed stocks.

    After receiving real-time candlestick data push, it will call back to this function. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateKL_pb2.Response|This parameter does not need to be processed directly in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, IPO data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * IPO data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        time_key|str|Time.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        open|float|Open.
        close|float|Close.
        high|float|High.
        low|float|Low.
        volume|float|Volume.
        turnover|float|Turnover.
        pe_ratio|float|P/E ratio.
        turnover_rate|float|Turnover rate.  (This field is in decimal form, so 0.01 is equivalent to 1%.)
        last_close|float|Close of the previous K-line.  (The close of the previous K-line. For efficiency reasons, the last_close of the first data may be 0.)
        k_type|[KLType](./quote.md#66)|Candlestick type.

* **Example**

```python
import time
from moomoo import *
class CurKlineTest(CurKlineHandlerBase):
     def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(CurKlineTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("CurKlineTest: error, msg: %s"% data)
            return RET_ERROR, data
        print("CurKlineTest ", data) # CurKlineTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = CurKlineTest()
quote_ctx.set_handler(handler) # Set real-time candlestick callback
ret, data = quote_ctx.subscribe(['US.AAPL'], [SubType.K_1M], session=Session.ALL) # Subscribe to the candlestick data type, OpenD starts to receive continuous push from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
CurKlineTest        code name             time_key    open   close    high    low  volume   turnover k_type  last_close
0  US.AAPL   APPLE  2025-04-07 05:15:00  180.39  180.26  180.46  180.2  1322.0  238340.48   K_1M         0.0
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Candlestick](./get-kl.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* **Options** related candlestick data, only supports 1 day, 1 minute, 5 minutes, 15 minutes and 60 minutes.
:::

---

# Real-time Time Frame Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time Time Frame callback, asynchronous processing of real-time Time Frame push of subscribed stocks.
    After receiving the real-time Time Frame data push, it will call back to this function. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateRT_pb2.Response|This parameter does not need to be processed directly in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, Time Frame data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Time Frame data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        time|str|Time.  (yyyy-MM-dd HH:mm:ssThe default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        is_blank|bool|Data status.  (False: normal data. True: forged data.)
        opened_mins|int|How many minutes have passed from 0 o'clock.
        cur_price|float|Current price.
        last_close|float|Yesterday's close.
        avg_price|float|Average price.  (For options, this field is None.)
        volume|float|Volume.
        turnover|float|Transaction amount.

* **Example**

```python
import time
from moomoo import *

class RTDataTest(RTDataHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(RTDataTest, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("RTDataTest: error, msg: %s"% data)
            return RET_ERROR, data
        print("RTDataTest ", data) # RTDataTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = RTDataTest()
quote_ctx.set_handler(handler) # Set real-time Time Frame push callback
ret, data = quote_ctx.subscribe(['US.AAPL'], [SubType.RT_DATA], session=Session.ALL) # Subscribe to the Time Frame type, OpenD starts to continuously receive pushes from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute   
```

* **Output**

```python
RTDataTest        code name                 time  is_blank  opened_mins  cur_price  last_close   avg_price   turnover  volume
0  US.AAPL   APPLE  2025-04-07 05:24:00     False          324     179.53      188.38  180.465762  651262.42    3624
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Time Frame Data](./get-rt.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Real-time Tick-by-Tick Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time callback, asynchronously processing the real-time push of subscribed stocks.
    After receiving real-time data push, it will call back to this function. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateTicker_pb2.Response|This parameter does not need to be processed directly in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, tick-by-tick data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Tick-by-tick data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        sequence|int|Sequence number.
        time|str|Transaction time.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        price|float|Transaction price.
        volume|float|Volume.  (shares)
        turnover|float|Transaction amount.
        ticker_direction|[TickerDirect](./quote.md#832)|Tick-By-Tick direction.
        type|[TickerType](./quote.md#9844)|Tick-By-Tick type.
        push_data_type|[PushDataType](./quote.md#2567)|Source of data.

* **Example**

```python
import time
from moomoo import *

class TickerTest(TickerHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(TickerTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("TickerTest: error, msg: %s"% data)
            return RET_ERROR, data
        print("TickerTest ", data) # TickerTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = TickerTest()
quote_ctx.set_handler(handler) # Set real-time push callback
ret, data = quote_ctx.subscribe(['US.AAPL'], [SubType.TICKER], session=Session.ALL) # Subscribe to the type by transaction, OpenD starts to receive continuous push from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
TickerTest        code name                     time   price  volume  turnover ticker_direction             sequence     type push_data_type
0  US.AAPL   APPLE  2025-04-07 05:25:44.116  179.81     9.0   1618.29          NEUTRAL  7490500033117159426  ODD_LOT          CACHE

```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Tick-By-Tick](./get-ticker.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* After the market connection is reconnected, during the disconnected period of OpenD pulls, the nearest (up to 50) Tick-By-Tick data is pushed, which can be distinguished by the Tick-By-Tick push type field
:::

---

# Real-time Broker Queue Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Real-time broker queue callback, asynchronous processing of real-time broker queue push of subscribed stocks.
    After receiving the real-time broker queue data push, it will call back to this function. You need to override on_recv_rsp in the derived class.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdateBroker_pb2.Response|This parameter does not need to be processed directly in the derived class.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>If ret == RET_OK, broker queue data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Broker queue data format as follows: 
        Field|Type|Description
        :-|:-|:-
        stock_code|str|Stock code.
        bid_frame_table|pd.DataFrame|Data from bid.
        ask_frame_table|pd.DataFrame|Data from ask.

        * Bid_frame_table format as follows: 
            Field|Type|Description
            :-|:-|:-
            code|str|Stock code.
            name|str|Stock name.
            bid_broker_id|int|Bid broker ID.
            bid_broker_name|str|Bid broker name.
            bid_broker_pos|int|Broker level.
            order_id|int|Exchange order ID.  (- Not the order ID returned by the order interface.
  - Only HK SF market quotes support returning this field.)
            order_volume|int|Order volume.  (Only HK SF market quotes support returning this field.)
        * Ask_frame_table format as follows: 
            Field|Type|Description
            :-|:-|:-
            code|str|Stock code.
            name|str|Stock name.
            ask_broker_id|int|Ask Broker ID.
            ask_broker_name|str|Ask Broker name.
            ask_broker_pos|int|Broker level.
            order_id|int|Exchange order ID.  (- Not the order ID returned by the order interface.
  - Only HK SF market quotes support returning this field.)
            order_volume|int|Order volume.  (Only HK SF market quotes support returning this field.)

* **Example**

```python
import time
from moomoo import *
    
class BrokerTest(BrokerHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, err_or_stock_code, data = super(BrokerTest, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("BrokerTest: error, msg: {}".format(err_or_stock_code))
            return RET_ERROR, data
        print("BrokerTest: stock: {} data: {} ".format(err_or_stock_code, data)) # BrokerTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = BrokerTest()
quote_ctx.set_handler(handler) # Set real-time broker push callback
ret, data = quote_ctx.subscribe(['HK.00700'], [SubType.BROKER]) # Subscribe to the broker type, OpenD starts to receive continuous push from the server
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
BrokerTest: stock: HK.00700 data: [        code     name  bid_broker_id                                    bid_broker_name  bid_broker_pos order_id order_volume
0   HK.00700  TENCENT           5338            J.P. Morgan Broking (Hong Kong) Limited               1      N/A          N/A
..       ...      ...            ...                                                ...             ...      ...          ...
36  HK.00700  TENCENT           8305  Futu Securities International (Hong Kong) Limited               4      N/A          N/A

[37 rows x 7 columns],         code     name  ask_broker_id                                ask_broker_name  ask_broker_pos order_id order_volume
0   HK.00700  TENCENT           1179  Huatai Financial Holdings (Hong Kong) Limited               1      N/A          N/A
..       ...      ...            ...                                            ...             ...      ...          ...
39  HK.00700  TENCENT           6996  China Investment Information Services Limited               1      N/A          N/A

[40 rows x 7 columns]] 
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Real-time Orderbook](./get-broker.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* Under the LV1 HK market quotes, the broker queue market data is not supported.
:::

---

# Get Market Snapshot

`get_market_snapshot(code_list)`

* **Description**

    Get market snapshot

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|Stock list  (Up to 400 targets can be requested each time. Data type of elements in the list is str.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, stock snapshot data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Stock snapshot data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        update_time|str|Current update time.  (yyyy-MM-dd HH:mm:ss. The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        last_price|float|Latest price.
        open_price|float|Open.
        high_price|float|High.
        low_price|float|Low.
        prev_close_price|float|Yesterday's close.
        volume|float|Volume.
        turnover|float|Turnover.
        turnover_rate|float|Turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        suspension|bool|Is suspended or not.  (True: suspension.)
        listing_date|str|Listing date.  (yyyy-MM-dd)
        equity_valid|bool|Is stock or not.  (The following equity-related fields will be legal only if this field is True.)
        issued_shares|int|Total shares.
        total_market_val|float|Total market value.  (Unit: yuan)
        net_asset|int|Net asset value.
        net_profit|int|Net profit.
        earning_per_share|float|Earnings per share.
        outstanding_shares|int|Shares outstanding.
        net_asset_per_share|float|Net assets per share.
        circular_market_val|float|Circulation market value.  (Unit: yuan)
        ey_ratio|float|Yield rate.  (This field is a ratio field, and % is not displayed.)
        pe_ratio|float|P/E ratio.  (This field is a ratio field, and % is not displayed.)
        pb_ratio|float|P/B ratio.  (This field is a ratio field, and % is not displayed.)
        pe_ttm_ratio|float|P/E ratio TTM.  (This field is a ratio field, and % is not displayed.)
        dividend_ttm|float|Dividend TTM, dividend.
        dividend_ratio_ttm|float|Dividend rate TTM.  (This field is in percentage form, so 20 is equivalent to 20%.)
        dividend_lfy|float|Dividend LFY, dividend of the previous year.
        dividend_lfy_ratio|float|Dividend rate LFY.  (This field is in percentage form, so 20 is equivalent to 20%.)
        stock_owner|str|The code of the underlying stock to which the warrant belongs or the code of the underlying stock of the option.
        wrt_valid|bool|Is warrant or not.  (The following warrant related fields will be legal if this field is True.)
        wrt_conversion_ratio|float|Conversion ratio.
        wrt_type|[WrtType](./quote.md#2421)|Warrant type.
        wrt_strike_price|float|Strike price.
        wrt_maturity_date|str|Maturity date.
        wrt_end_trade|str|Last trading time.
        wrt_leverage|float|Leverage ratio.  (Unit: times)
        wrt_ipop|float|in/out of the money.  (This field is in percentage form, so 20 is equivalent to 20%.)
        wrt_break_even_point|float|Breakeven point.
        wrt_conversion_price|float|Conversion price.
        wrt_price_recovery_ratio|float|Price recovery ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
        wrt_score|float|Comprehensive score of warrant.
        wrt_code|str|The underlying stock of the warrant (This field has been deprecated and changed to stock_owner.).
        wrt_recovery_price|float|Warrant recovery price.
        wrt_street_vol|float|Warrant Outstanding quantity.
        wrt_issue_vol|float|Warrant issuance.
        wrt_street_ratio|float|Outstanding percentage.  (This field is in percentage form, so 20 is equivalent to 20%.)
        wrt_delta|float|Delta value of warrant.
        wrt_implied_volatility|float|Warrant implied volatility.
        wrt_premium|float|Warrant premium.  (This field is in percentage form, so 20 is equivalent to 20%.)
        wrt_upper_strike_price|float|Upper bound price.  (Only Inline Warrant supports this field.)
        wrt_lower_strike_price|float|lower bound price.  (Only Inline Warrant supports this field.)
        wrt_inline_price_status|[PriceType](./quote.md#9794)|in/out of bounds  (Only Inline Warrant supports this field.)
        wrt_issuer_code|str|Issuer code.
        option_valid|bool|Is option or not.  (The following option related fields will be legal when this field is True.)
        option_type|[OptionType](./quote.md#9598)|Option type.
        strike_time|str|The option exercise date.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        option_strike_price|float|Strike price.
        option_contract_size|float|Number of stocks per contract.
        option_open_interest|int|Total open contract number.
        option_implied_volatility|float|Implied volatility.
        option_premium|float|Premium.
        option_delta|float|Greek value Delta.
        option_gamma|float|Greek value Gamma.
        option_vega|float|Greek value Vega.
        option_theta|float|Greek value Theta.
        option_rho|float|Greek value Rho.
        index_option_type|[IndexOptionType](./quote.md#2866)|Index option type.
        option_net_open_interest|int|Net open contract number.  (Only HK options support this field.)
        option_expiry_date_distance|int|The number of days from the expiry date, a negative number means it has expired.
        option_contract_nominal_value|float|Contract nominal amount.  (Only HK options support this field.)
        option_owner_lot_multiplier|float|Equal number of underlying stocks.  (Index options do not have this field, only HK options support this field.)
        option_area_type|[OptionAreaType](./quote.md#3628)|Option type (by exercise time).
        option_contract_multiplier|float|Contract multiplier.
        plate_valid|bool|Is plate or not.  (The following plate related fields will be legal when this field is True.)
        plate_raise_count|int|Number of stocks that raises in the plate.
        plate_fall_count|int|Number of stocks that falls in the plate.
        plate_equal_count|int|Number of stocks that dose not change in price in the plate.
        index_valid|bool|Is index or not.  (The following index related fields will be legal when this field is True.)
        index_raise_count|int|Number of stocks that raises in the plate.
        index_fall_count|int|Number of stocks that falls in the plate.
        index_equal_count|int|Number of stocks that dose not change in the plate.
        lot_size|int|The number of shares per lot, stock options represent the number of shares per contract  (Index options do not have this field.), and futures represent contract multipliers.
        price_spread|float|The current upward price difference.  (That is, the quotation difference between ask price and sell 1.)
        ask_price|float|Ask price.
        bid_price|float|Bid price.
        ask_vol|float|Ask volume.
        bid_vol|float|Bid volume.
        enable_margin|bool|Whether financing is available (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        mortgage_ratio|float|Stock mortgage rate (Deprecated).
        long_margin_initial_ratio|float|The initial margin rate of financing (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        enable_short_sell|bool|Whether short-selling is available (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        short_sell_rate|float|Short-selling reference rate (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        short_available_volume|int|Remaining quantity that can be sold short (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        short_margin_initial_ratio|float|The initial margin rate for short selling (Deprecated).  (Please use [Get Margin Data](../trade/get-margin-ratio.html).)
        sec_status|[SecurityStatus](./quote.md#4415)|Stock status.
        amplitude|float|Amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        avg_price|float|Average price.
        bid_ask_ratio|float|The Committee.  (This field is in percentage form, so 20 is equivalent to 20%.)
        volume_ratio|float|Volume ratio.
        highest52weeks_price|float|Highest price in 52 weeks.
        lowest52weeks_price|float|Lowest price in 52 weeks .
        highest_history_price|float|Highest historical price.
        lowest_history_price|float|Lowest historical price.
        pre_price|float|Pre-market price.
        pre_high_price|float|Highest pre-market price.
        pre_low_price|float|Lowest pre-market price.
        pre_volume|int|Pre-market volume.
        pre_turnover|float|Pre-market turnover.
        pre_change_val|float|Pre-market change.
        pre_change_rate|float|Pre-market change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        pre_amplitude|float|Pre-market amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_price|float|After-hours price.
        after_high_price|float|Highest price after-hours.
        after_low_price|float|Lowest price after-hours.
        after_volume|int|After-hours trading volume.  (The Sci-tech Innovation Board supports this data.)
        after_turnover|float|After-hours turnover.  (The Sci-tech Innovation Board supports this data.)
        after_change_val|float|After-hours change.
        after_change_rate|float|After-hours change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_amplitude|float|After-hours amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_price|float|Overnight price.
        overnight_high_price|float|Overnight high.
        overnight_low_price|float|Overnight low.
        overnight_volume|int|Overnight volume.
        overnight_turnover|float|Overnight turnover.
        overnight_change_val|float|Overnight change.
        overnight_change_rate|float|Overnight change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_amplitude|float|Overnight amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        future_valid|bool|Is futures or not.
        future_last_settle_price|float|Yesterday's close.
        future_position|float|Holding position.
        future_position_change|float|Change in position.
        future_main_contract|bool|Is future main contract or not.
        future_last_trade_time|str|The last trading time.  (Main, current month and next month futures do not have this field.)
        trust_valid|bool|Is fund or not.
        trust_dividend_yield|float|Dividend rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        trust_aum|float|Asset scale.  (Unit: yuan)
        trust_outstanding_units|int|Total circulation.
        trust_netAssetValue|float|Net asset value.
        trust_premium|float|Premium.  (This field is in percentage form, so 20 is equivalent to 20%.)
        trust_assetClass|[AssetClass](./quote.md#4696)|Asset class.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_market_snapshot(['HK.00700', 'US.AAPL'])
if ret == RET_OK:
    print(data)
    print(data['code'][0])    # Take the first stock code
    print(data['code'].values.tolist())   # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
   code  name              update_time  last_price  open_price  high_price  low_price  prev_close_price     volume      turnover  turnover_rate  suspension listing_date  lot_size  price_spread  stock_owner  ask_price  bid_price  ask_vol  bid_vol  enable_margin  mortgage_ratio  long_margin_initial_ratio  enable_short_sell  short_sell_rate  short_available_volume  short_margin_initial_ratio  amplitude  avg_price  bid_ask_ratio  volume_ratio  highest52weeks_price  lowest52weeks_price  highest_history_price  lowest_history_price  close_price_5min  after_volume  after_turnover sec_status  equity_valid  issued_shares  total_market_val     net_asset    net_profit  earning_per_share  outstanding_shares  circular_market_val  net_asset_per_share  ey_ratio  pe_ratio  pb_ratio  pe_ttm_ratio  dividend_ttm  dividend_ratio_ttm  dividend_lfy  dividend_lfy_ratio  wrt_valid  wrt_conversion_ratio wrt_type  wrt_strike_price  wrt_maturity_date  wrt_end_trade  wrt_recovery_price  wrt_street_vol  \
0  HK.00700  TENCENT      2025-04-07 16:09:07      435.40      441.80      462.40     431.00            497.80  123364114.0  5.499476e+10          1.341       False   2004-06-16       100          0.20          NaN      435.4     435.20   281300    17300            NaN             NaN                        NaN                NaN              NaN                     NaN                         NaN      6.308    445.792        -68.499         5.627             547.00000           294.400000             706.100065            -13.202011            431.60             0    0.000000e+00     NORMAL          True     9202391012      4.006721e+12  1.051300e+12  2.095753e+11             22.774          9202391012         4.006721e+12              114.242     0.199    19.118     3.811        19.118          3.48                0.80          3.48               0.799      False                   NaN      N/A               NaN                NaN            NaN                 NaN             NaN   
1   US.AAPL    APPLE  2025-04-07 05:30:43.301      188.38      193.89      199.88     187.34            203.19  125910913.0  2.424473e+10          0.838       False   1980-12-12         1          0.01          NaN      180.8     180.48       29      400            NaN             NaN                        NaN                NaN              NaN                     NaN                         NaN      6.172    192.554         86.480         2.226             259.81389           163.300566             259.813890              0.053580            188.93       3151311    5.930968e+08     NORMAL          True    15022073000      2.829858e+12  6.675809e+10  9.133420e+10              6.080         15016677308         2.828842e+12                4.444     1.417    30.983    42.389        29.901          0.99                0.53          0.98               0.520      False                   NaN      N/A               NaN                NaN            NaN                 NaN             NaN   

   wrt_issue_vol  wrt_street_ratio  wrt_delta  wrt_implied_volatility  wrt_premium  wrt_leverage  wrt_ipop  wrt_break_even_point  wrt_conversion_price  wrt_price_recovery_ratio  wrt_score  wrt_upper_strike_price  wrt_lower_strike_price wrt_inline_price_status  wrt_issuer_code  option_valid option_type  strike_time  option_strike_price  option_contract_size  option_open_interest  option_implied_volatility  option_premium  option_delta  option_gamma  option_vega  option_theta  option_rho  option_net_open_interest  option_expiry_date_distance  option_contract_nominal_value  option_owner_lot_multiplier option_area_type  option_contract_multiplier index_option_type  index_valid  index_raise_count  index_fall_count  index_equal_count  plate_valid  plate_raise_count  plate_fall_count  plate_equal_count  future_valid  future_last_settle_price  future_position  future_position_change  future_main_contract  future_last_trade_time  trust_valid  trust_dividend_yield  trust_aum  \
0            NaN               NaN        NaN                     NaN          NaN           NaN       NaN                   NaN                   NaN                       NaN        NaN                     NaN                     NaN                     N/A              NaN         False         N/A          NaN                  NaN                   NaN                   NaN                        NaN             NaN           NaN           NaN          NaN           NaN         NaN                       NaN                          NaN                            NaN                          NaN              N/A                         NaN               N/A        False                NaN               NaN                NaN        False                NaN               NaN                NaN         False                       NaN              NaN                     NaN                   NaN                     NaN        False                   NaN        NaN   
1            NaN               NaN        NaN                     NaN          NaN           NaN       NaN                   NaN                   NaN                       NaN        NaN                     NaN                     NaN                     N/A              NaN         False         N/A          NaN                  NaN                   NaN                   NaN                        NaN             NaN           NaN           NaN          NaN           NaN         NaN                       NaN                          NaN                            NaN                          NaN              N/A                         NaN               N/A        False                NaN               NaN                NaN        False                NaN               NaN                NaN         False                       NaN              NaN                     NaN                   NaN                     NaN        False                   NaN        NaN   

   trust_outstanding_units  trust_netAssetValue  trust_premium trust_assetClass pre_price pre_high_price pre_low_price pre_volume pre_turnover pre_change_val pre_change_rate pre_amplitude after_price after_high_price after_low_price after_change_val after_change_rate after_amplitude overnight_price overnight_high_price overnight_low_price overnight_volume overnight_turnover overnight_change_val overnight_change_rate overnight_amplitude  
0                      NaN                  NaN            NaN              N/A       N/A            N/A           N/A        N/A          N/A            N/A             N/A           N/A         N/A              N/A             N/A              N/A               N/A             N/A             N/A                  N/A                 N/A              N/A                N/A                  N/A                   N/A                 N/A  
1                      NaN                  NaN            NaN              N/A    180.68         181.98        177.47     276016  49809244.83           -7.7          -4.087         2.394       186.6          188.639          186.44            -1.78            -0.944          1.1673          176.94                186.5               174.4           533115        94944250.56               -11.44                -6.072              6.4231  
HK.00700
['HK.00700', 'US.AAPL']
```

:::tip Interface Limitations
* Request up to 60 snapshots every 30 seconds
* For each request, the maximum number of stock codes supported by the parameter *code_list* is 400.

:::

---

# Get Real-time Quote

`get_stock_quote(code_list)`

* **Description**

    To get real-time quotes of subscribed securities, you must subscribe first.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|Stock list. Data type of elements in the list is str.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, quotation data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * quotation data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        data_date|str|Date.
        data_time|str|Time of latest price.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        last_price|float|Latest price.
        open_price|float|Open.
        high_price|float|High.
        low_price|float|Low.
        prev_close_price|float|Yesterday's close.
        volume|float|Volume.
        turnover|float|Turnover.
        turnover_rate|float|Turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        amplitude|int|Amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        suspension|bool|Whether trading is suspended.  (True: suspension)
        listing_date|str|Listing date.  (yyyy-MM-dd)
        price_spread|float|Spread.
        dark_status|[DarkStatus](./quote.md#6341)|Grey market transaction status.
        sec_status|[SecurityStatus](./quote.md#4415)|Stock status.
        strike_price|float|Strike price.
        contract_size|float|Contract size.
        open_interest|int|Number of open positions.
        implied_volatility|float|Implied volatility.  (This field is in percentage form, so 20 is equivalent to 20%.)
        premium|float|Premium.  (This field is in percentage form, so 20 is equivalent to 20%.)
        delta|float|Greek value Delta.
        gamma|float|Greek value Gamma.
        vega|float|Greek value Vega.
        theta|float|Greek value Theta.
        rho|float|Greek value Rho.
        index_option_type|[IndexOptionType](./quote.md#2866)|Index option type.
        net_open_interest|int|Net open contract number.  (Only HK options support this field.)
        expiry_date_distance|int|The number of days from the expiry date.  (a negative number means it has expired.)
        contract_nominal_value|float|Contract nominal amount.  (Only HK options support this field.)
        owner_lot_multiplier|float|Equal number of underlying stocks.  (Index options do not have this field , only HK options support this field.)
        option_area_type|[OptionAreaType](./quote.md#3628)|Option type (by exercise time).
        contract_multiplier|float|Contract multiplier.
        pre_price|float|Pre-market price.
        pre_high_price|float|Pre-market high.
        pre_low_price|float|Pre-market low.
        pre_volume|int|Pre-market volume.
        pre_turnover|float|Pre-market turnover.
        pre_change_val|float|Pre-market change.
        pre_change_rate|float|Pre-market change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        pre_amplitude|float|Pre-market amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_price|float|After-hours price.
        after_high_price|float|After-hours high.
        after_low_price|float|After-hours low.
        after_volume|int|After-hours volume.  (The Sci-tech Innovation Board supports this data.)
        After_turnover|float|After-hours turnover.  (The Sci-tech Innovation Board supports this data.)
        after_change_val|float|After-hours change.
        after_change_rate|float|After-hours change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        after_amplitude|float|After-hours amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_price|float|Overnight price.
        overnight_high_price|float|Overnight high.
        overnight_low_price|float|Overnight low.
        overnight_volume|int|Overnight volume.
        overnight_turnover|float|Overnight turnover.
        overnight_change_val|float|Overnight change.
        overnight_change_rate|float|Overnight change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        overnight_amplitude|float|Overnight amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
        last_settle_price|float|Yesterday's close.  (Specific field for futures.)
        position|float|Holding position.  (Specific field for futures.)
        position_change|float|Daily position change.  (Specific field for futures.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.QUOTE], subscribe_push=False)
# Subscribe to the K line type first. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK: # Subscription successful
     ret, data = quote_ctx.get_stock_quote(['US.AAPL']) # Get real-time data of subscription stock quotes
     if ret == RET_OK:
         print(data)
         print(data['code'][0]) # Take the first stock code
         print(data['code'].values.tolist()) # Convert to list
     else:
         print('error:', data)
else:
     print('subscription failed', err_message)
quote_ctx.close() # Close the current connection, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
code name   data_date     data_time  last_price  open_price  high_price  low_price  prev_close_price     volume      turnover  turnover_rate  amplitude  suspension listing_date  price_spread dark_status sec_status strike_price contract_size open_interest implied_volatility premium delta gamma vega theta  rho net_open_interest expiry_date_distance contract_nominal_value owner_lot_multiplier option_area_type contract_multiplier last_settle_price position position_change index_option_type  pre_price  pre_high_price  pre_low_price  pre_volume  pre_turnover  pre_change_val  pre_change_rate  pre_amplitude  after_price  after_high_price  after_low_price  after_volume  after_turnover  after_change_val  after_change_rate  after_amplitude  overnight_price  overnight_high_price  overnight_low_price  overnight_volume  overnight_turnover  overnight_change_val  overnight_change_rate  overnight_amplitude
0  US.AAPL   APPLE  2025-04-07  05:37:21.794      188.38      193.89      199.88     187.34            203.19  125910913.0  2.424473e+10          0.838      6.172       False   1980-12-12          0.01         N/A     NORMAL          N/A           N/A           N/A                N/A     N/A   N/A   N/A  N/A   N/A  N/A               N/A                  N/A                    N/A                  N/A              N/A                 N/A               N/A      N/A             N/A               N/A     181.43          181.98         177.47      288853   52132735.18           -6.95           -3.689          2.394        186.6           188.639           186.44       3151311    5.930968e+08             -1.78             -0.944           1.1673           176.94                 186.5                174.4            533115         94944250.56                -11.44                 -6.072               6.4231
US.AAPL
['US.AAPL']
```

:::tip Tips
* This API provides the function to obtain real-time data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time Quote Callback](./update-stock-quote.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Get Real-time Order Book

`get_order_book(code, num=10, order_book_type=None)`

* **Description**

    To get the real-time order book of subscribed stocks, you must subscribe first.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    num|int|The requested number of price levels.  (For the upper limit of the number of price levels, please refer to [Details of price levels](../qa/quote.md#2126).)
    order_book_type|[OrderBookType](./quote.md#9106)|Order book type, returns normal order book by default if not specified


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, plate data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order Book format as follows：
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        svr_recv_time_bid|str|The time when moomoo server receives order book of bid from the exchange.  (Sometimes the time is zero, e.g. server reboot or first push of cached data.)
        svr_recv_time_ask|str|The time when moomoo server receives order book of ask from the exchange.  (Sometimes the time is zero, e.g. server reboot or first push of cached data.)
        order_book_type|[OrderBookType](./quote.md#9106)|Order book type
        Bid|list|Each tuple contains the following information：Bid price, bid volume, order qty of bid, order details of bid.  (Order details of ask
  - Details: Exchange order ID. Order volume.
  - Up to 1000 order details of ask with HK SF market quotes.  
  - Other quote rights does not support access to such details.)
        Ask|list|Each tuple contains the following information：Ask price, ask volume, order qty of ask, order details of ask.  (Order details of ask
  - Details: Exchange order ID. Order volume.
  - Up to 1000 order details of ask with HK SF market quotes.  
  - Other quote rights does not support access to such details.)

        The format of Bid and Ask fields as follows：  

          'Bid': [ (bid_price1, bid_volume1, order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }), (bid_price2, bid_volume2, order_num,  {'orderid1': order_volume1, 'orderid2': order_volume2, …… }),…]
          'Ask': [ (ask_price1, ask_volume1，order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }), (ask_price2, ask_volume2, order_num, {'orderid1': order_volume1, 'orderid2': order_volume2, …… }),…] 

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret_sub = quote_ctx.subscribe(['US.AAPL'], [SubType.ORDER_BOOK], subscribe_push=False)[0]
# First subscribe to the order type. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK:  # Successfully subscribed
    ret, data = quote_ctx.get_order_book('US.AAPL', num=3)  # Get 3 files of real-time panning data once
    if ret == RET_OK:
        print(data)
    else:
        print('error:', data)
else:
    print('subscription failed')
quote_ctx.close()  # Close the current connection, OpenD will automatically cancel the subscription of the corresponding stock in 1 minute
```

* **Output**

```python
{'code': 'US.AAPL', 'name': 'APPLE', 'svr_recv_time_bid': '2025-04-07 05:39:20.352', 'svr_recv_time_ask': '2025-04-07 05:39:20.352', 'order_book_type': 'NORMAL', 'Bid': [(181.17, 227.0, 2, {}), (181.15, 2.0, 2, {}), (181.12, 100.0, 1, {})], 'Ask': [(181.71, 200.0, 1, {}), (181.79, 9.0, 1, {}), (181.9, 616.0, 3, {})]}
```

:::tip Interface Limitations
* The time field in which the moomoo server receives data from the exchange. Only supports A-share Market stocks, HK stocks, ETFs, warrants, bulls and bears, and this data is only available at the opening time.
* The time field in which the moomoo server receives data from the exchange. The receiving time of some data is zero, such as server restart or cached data pushed for the first time.
:::

:::tip Tips
* This API provides the function of obtaining real-time data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time OrderBook Callback](./update-order-book.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* The real-time order book data will be returned during the current trading session for US stocks, with no need to set the session parameter.
:::

---

# Get Real-time Candlestick

`get_cur_kline(code, num, ktype=SubType.K_DAY, autype=AuType.QFQ)`

* **Description**

    Get real-time candlestick data of subscribed stocks, you must subscribe first.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    num|int|The number of candlesticks.  (Up to 1000.)
    ktype|[KLType](./quote.md#66)|Candlestick type.
    autype|[AuType](./quote.md#7071)|Type of adjustment.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, IPO data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * IPO data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        time_key|str|Time.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        open|float|Open.
        close|float|Close.
        high|float|High.
        low|float|Low.
        volume|int|Volume.
        turnover|float|Turnover.
        pe_ratio|float|P/E ratio.
        turnover_rate|float|Turnover rate.  (This field is in decimal form, so 0.01 is equivalent to 1%.)
        last_close|float|Close of the previous K-line.  (The close of the previous K-line. For efficiency reasons, the last_close of the first data may be 0.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.K_DAY], subscribe_push=False, session=Session.ALL)
# First subscribe to the candlestick type. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK:  # Successfully subscribed
    ret, data = quote_ctx.get_cur_kline('US.AAPL', 2, SubType.K_DAY, AuType.QFQ)  # Get the latest 2 candlestick data of US.AAPL
    if ret == RET_OK:
        print(data)
        print(data['turnover_rate'][0])   # Take the first turnover rate
        print(data['turnover_rate'].values.tolist())   # Convert to list
    else:
        print('error:', data)
else:
    print('subscription failed', err_message)
quote_ctx.close()  # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
code name             time_key    open   close    high     low     volume      turnover  pe_ratio  turnover_rate  last_close
0  US.AAPL   APPLE  2025-04-03 00:00:00  205.54  203.19  207.49  201.25  103419006.0  2.111773e+10    33.419        0.00689      223.89
1  US.AAPL   APPLE  2025-04-04 00:00:00  193.89  188.38  199.88  187.34  125910913.0  2.424473e+10    30.983        0.00838      203.19
0.00689
[0.00689, 0.00838]
```

:::tip Interface Limitations
* This interface is to obtain real-time candlestick, which can obtain the nearest 1000 at most. To get historical candlestick, please refer to [Get historical candlestick](../quote/request-history-kline.md).
* Only a stock of daily timeframe and above have P/E ratio and turnover ratio fields.
* **Options** related candlestick data, only supports 1 day, 1 minute, 5 minutes, 15 minutes and 60 minutes.
:::

:::tip Tips
* This API provides the function of obtaining candlestick data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time Candlestick Callback](./update-kl.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Get Real-time Time Frame Data

`get_rt_data(code)`

* **Description**

    Obtain real-time tick-by-tick data for a specified stock. (Require real-time data subscription.)

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, Time Frame data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Time Frame data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        time|str|Time.  (yyyy-MM-dd HH:mm:ss The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        is_blank|bool|Data status.  (False: normal data.True: forged data.)
        opened_mins|int|How many minutes have passed from 0 o'clock.
        cur_price|float|Current price.
        last_close|float|Yesterday's close.
        avg_price|float|Average price.  (For options, this field is N/A.)
        volume|float|Volume.
        turnover|float|Transaction amount.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.RT_DATA], subscribe_push=False, session=Session.ALL)
# Subscribe to the Time Frame data type first. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK:   # Successfully subscribed
    ret, data = quote_ctx.get_rt_data('US.AAPL')   # Get Time Frame data once
    if ret == RET_OK:
        print(data)
    else:
        print('error:', data)
else:
    print('subscription failed', err_message)
quote_ctx.close()   # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
code  name                 time  is_blank  opened_mins  cur_price  last_close   avg_price   volume     turnover
0    US.AAPL   APPLE  2025-04-06 20:01:00     False         1201     183.00      188.38  181.643916    9463  1718896.38
..      ...    ...                  ...       ...          ...        ...         ...         ...      ...          ...
586  US.AAPL   APPLE  2025-04-07 05:47:00     False          347     181.26      188.38  180.555673     661   119859.75

[587 rows x 10 columns]
```

:::tip Tips
* This API provides the function of obtaining real-time data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time Time Frame Callback](./update-rt.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Get Real-time Tick-by-Tick

`get_rt_ticker(code, num=500)`

* **Description**

    To get real-time tick-by-tick of subscribed stocks. (Require real-time data subscription.)

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    num|int|Number of recent tick-by-tick.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, tick-by-tick data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Tick-by-tick data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        sequence|int|Sequence number.
        time|str|Transaction time.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        price|float|Transaction price.
        volume|int|Volume.  (shares)
        turnover|float|Transaction amount.
        ticker_direction|[TickerDirect](./quote.md#832)|Tick-By-Tick direction.
        type|[TickerType](./quote.md#9844)|Tick-By-Tick type.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret_sub, err_message = quote_ctx.subscribe(['US.AAPL'], [SubType.TICKER], subscribe_push=False, session=Session.ALL)
# First subscribe to each type. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push to the script temporarily
if ret_sub == RET_OK: # Subscription successful
     ret, data = quote_ctx.get_rt_ticker('US.AAPL', 2) # Get the last 2 transactions of Hong Kong stocks 00700
     if ret == RET_OK:
         print(data)
         print(data['turnover'][0]) # Take the first transaction amount
         print(data['turnover'].values.tolist()) # Convert to list
     else:
         print('error:', data)
else:
     print('subscription failed', err_message)
quote_ctx.close() # Close the current link, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
code name                     time   price  volume  turnover ticker_direction             sequence     type
0  US.AAPL   APPLE  2025-04-07 05:50:23.745  181.70       2    363.40          NEUTRAL  7490506385373790208  ODD_LOT
1  US.AAPL   APPLE  2025-04-07 05:50:24.170  181.73       1    181.73          NEUTRAL  7490506389668757504  ODD_LOT
363.4
[363.4, 181.73]
```

:::tip Interface Limitations
* You can get up to the latest 1000 tick-by-tick data, more historical tick-by-tick data is not yet available
* Under the authority of LV1 HK futures and options market, tick-by-tick data is not available
:::

:::tip Tips
* This API provides the function of obtaining real-time data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time Tick-By-Tick Callback](./update-ticker.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
:::

---

# Get Real-time Broker Queue

## get_broker_queue

`get_broker_queue(code)`

* **Description**

    Obtain real-time data of market participants on the order book. (Require real-time data subscription.)

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">bid_frame_table</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, queue of bid brokers is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
        <tr>
            <td rowspan="2">ask_frame_table</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, queue of ask brokers is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Queue of bid brokers format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        bid_broker_id|int|Bid broker ID.
        bid_broker_name|str|Bid broker name.
        bid_broker_pos|int|Broker level.
        order_id|int|Exchange order ID.  (- Not the order ID returned by the order interface.
  - Only HK SF market quotes support returning this field.)
        order_volume|int|Order volume.  (Only HK SF market quotes support returning this field.)
    * Queue of ask brokers format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        ask_broker_id|int|Ask Broker ID.
        ask_broker_name|str|Ask Broker name.
        ask_broker_pos|int|Broker level.
        order_id|int|Exchange order ID.  (- Not the order ID returned by the order interface.
  - Only HK SF market quotes support returning this field.)
        order_volume|int|Order volume.  (Only HK SF market quotes support returning this field.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret_sub, err_message = quote_ctx.subscribe(['HK.00700'], [SubType.BROKER], subscribe_push=False)
# First subscribe to the broker queue type. After the subscription is successful, OpenD will continue to receive pushes from the server, False means that there is no need to push the data to the script temporarily
if ret_sub == RET_OK: # Subscription successful
     ret, bid_frame_table, ask_frame_table = quote_ctx.get_broker_queue('HK.00700') # Get a broker queue data
     if ret == RET_OK:
         print(bid_frame_table)
     else:
         print('error:', bid_frame_table)
else:
     print(err_message)
quote_ctx.close() # Close the current connection, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
    code     name  bid_broker_id                                    bid_broker_name  bid_broker_pos order_id order_volume
0   HK.00700  TENCENT           5338            J.P. Morgan Broking (Hong Kong) Limited               1      N/A          N/A
..       ...      ...            ...                                                ...             ...      ...          ...
36  HK.00700  TENCENT           8305  Futu Securities International (Hong Kong) Limited               4      N/A          N/A

[37 rows x 7 columns]
```

:::tip Tips
* This API provides the function of obtaining real-time data at one time. If you need to obtain pushed data continuously, please refer to the [Real-time Broker Queue Callback](./update-broker.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505).
* Under the LV1 HK market quotes, the broker queue market data is not supported.
:::

---

# Get Market Status of Securities

`get_market_state(code_list)`

* **Description**

    Get market status of underlying security

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|A list of security codes that need to query for market status.  (Data type of elements in the list is str.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, market status data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Market status data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Security code.
        stock_name|str|Security name.
        market_state|[MarketState](./quote.md#8663)|Market state.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_market_state(['SZ.000001', 'HK.00700'])
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code         stock_name   market_state
0  SZ.000001    Ping An Bank  AFTERNOON
1  HK.00700     Tencent       AFTERNOON
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* The maximum number of stock codes for each request is 400.
:::

---

# Get Capital Flow

`get_capital_flow(stock_code, period_type = PeriodType.INTRADAY, start=None, end=None)`

* **Description**

    Get the flow of a specific stock

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    stock_code|str|Stock code.
    period_type|[PeriodType](./quote.md#2884)|Period Type.
    start|str|Start time.  (Fotmat：yyyy-MM-dd 
For example: "2017-06-20".)
    end|str|End time.  (Fotmat：yyyy-MM-dd 
For example: "2017-06-20".)


    * The combination of ***start*** and ***end*** is as follows
        start type|end type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 365 days before ***end***.
        str|None|***end*** is 365 days after ***start***.
        None|None|***end*** is the current date, ***start*** is 365 days before.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, capital flow data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Capital flow data format as follows: 
        Field|Type|Description
        :-|:-|:-
        in_flow|float|Net inflow of capital.
        main_in_flow|float|Block Orders Net Inflow.  (Only applicable to historical period (Day, Week, Month).)
        super_in_flow|float|Extra-large Orders Net Inflow. 
        big_in_flow|float|Large Orders Net Inflow. 
        mid_in_flow|float|Medium Orders Net Inflow. 
        sml_in_flow|float|Small Orders Net Inflow. 
        capital_flow_item_time|str|Start time string.  (Format: yyyy-MM-dd HH:mm:ss
Unit: minute.)
        last_valid_time|str|Last valid time string of data.  (Only applicable to intraday period.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_capital_flow("HK.00700", period_type = PeriodType.INTRADAY)
if ret == RET_OK:
    print(data)
    print(data['in_flow'][0]) # Take the first net inflow of capital
    print(data['in_flow'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    last_valid_time       in_flow  ...  main_in_flow  capital_flow_item_time
0               N/A -1.857915e+08  ... -1.066828e+08     2021-06-08 00:00:00
..              ...           ...  ...           ...                     ...
245             N/A  2.179240e+09  ...  2.143345e+09     2022-06-08 00:00:00

[246 rows x 8 columns]
-185791500.0
[-185791500.0, -18315000.0, -672100100.0, -714394350.0, -698391950.0, -818886750.0, 304827400.0, 73026200.0, -2078217500.0, 
..                   ...           ...                    ...
2031460.0, 638067040.0, 622466600.0, -351788160.0, -328529240.0, 715415020.0, 76749700.0, 2179240320.0]
```

:::tip Interface Limitations
* A maximum of 30 requests per 30 seconds.
* Support stocks, warrants, funds and crypto.
* Historical period (day, month, year) Only provides data for the latest 1 year; Intraday period only provides data for the latest day.
* Data with historical period (day, month, year), is only supported for the last 2 years. While Data with intraday period is only supported for the latest day.
* Output data only includes tha data during Regular Trading Hours, not the data during Pre and Post-Market Hours.       
:::

---

# Get Capital Distribution

`get_capital_distribution(stock_code)`

* **Description**

    Access to capital distribution

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    stock_code|str|Stock code.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, stock fund distribution data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Stock fund distribution data format as follows: 
        Field|Type|Description
        :-|:-|:-
        capital_in_super|float|Inflow capital quota, extra-large order.
        capital_in_big|float|Inflow capital quota, large order.
        capital_in_mid|float|Inflow capital quota, midium order.
        capital_in_small|float|Inflow capital quota, small order.
        capital_out_super|float|Outflow capital quota, extra-large order.
        capital_out_big|float|Outflow capital quota, large order.
        capital_out_mid|float|Outflow capital quota, midium order.
        capital_out_small|float|Outflow capital quota, small order.
        update_time|str|Updated time string.  (Fotmat：yyyy-MM-dd HH:mm:ss)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_capital_distribution("HK.00700")
if ret == RET_OK:
    print(data)
    print(data['capital_in_big'][0]) # Take the amount of inflow capital of the first article, big order
    print(data['capital_in_big'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
   capital_in_super  capital_in_big  ...  capital_out_small          update_time
0      2.261085e+09    2.141964e+09  ...       2.887413e+09  2022-06-08 15:59:59

[1 rows x 9 columns]
2141963720.0
[2141963720.0]
```

:::tip Interface Limitations
* A maximum of 30 requests per 30 seconds
* Support stocks, warrants, funds and crypto.
* For more capital flow introduction, please refer to [here](https://support.futunn.com/en-us/topic498?lang=en-US).
* Output data only includes tha data during Regular Trading Hours, not the data during Pre and Post-Market Hours.       
:::

---

# Get Plates of Stocks

`get_owner_plate(code_list)`

* **Description**

    Get the information of plates to which the stocks belong

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|Stock code list.  (Only supports underlying stocks and indexes. Data type of elements in the list is str.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, data of the sector is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Data of the sector format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Securities code.
        name|str|Stock name.
        plate_code|str|Plate code.
        plate_name|str|Plate name.
        plate_type|[Plate](./quote.md#978)|Plate type.  (industry or conceptual.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

code_list = ['HK.00001']
ret, data = quote_ctx.get_owner_plate(code_list)
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['plate_code'].values.tolist()) # Convert plate code to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code          name          plate_code                            plate_name plate_type
0   HK.00001  CKH HOLDINGS  HK.HSI Constituent  ConstituentStocks in Hang Seng Index      OTHER
..       ...           ...                 ...                                   ...        ...
8   HK.00001  CKH HOLDINGS           HK.BK1983                                HK ADR      OTHER

[9 rows x 5 columns]
HK.00001
['HK.HSI Constituent', 'HK.GangGuTong', 'HK.BK1000', 'HK.BK1061', 'HK.BK1107', 'HK.BK1331', 'HK.BK1600', 'HK.BK1922', 'HK.BK1983']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* The maximum number of stocks of each request list is 200
* Only supports stocks and indices
:::

---

# Get Historical Candlesticks

`request_history_kline(code, start=None, end=None, ktype=KLType.K_DAY, autype=AuType.QFQ, fields=[KL_FIELD.ALL], max_count=1000, page_req_key=None, extended_time=False)`

* **Description**

    Get historical candlesticks

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    start|str|Start time.  (Format: yyyy-MM-dd
For example: "2017-06-20".)
    end|str|End time.  (Format: yyyy-MM-dd
For example: "2017-07-20".)
    ktype|[KLType](./quote.md#66)|Candlestick type.
    autype|[AuType](./quote.md#7071)|Type of adjustment.
    fields|[KL_FIELD](./quote.md#5803)|List of fields to be returned.
    max_count|int|The maximum number of candlesticks returned in this request.  (- Sending None indicates that all data between start and end is returned. 
  - Note: OpenD requests all the data and then sends it to the script. If the number of candlesticks you want to obtain is more than 1000, it is recommended to select paging to prevent from timeout.)
    page_req_key|bytes|The key of the page request. If the number of candlesticks between start and end is more than max_count, then None should be passed at the first time you call this interface, and the page_req_key returned by the last call must be passed in the subsequent pagerequests.
    extended_time|bool|Need pre-market and after-hours data for US stocks or not. False: not need, True: need.
    session|[Session](./quote.md#8688)|Get US stocks historical k-line in session  (- Only used to get historical k-line for US stocks in session.
  - If you want to get 24H historical k-line data of US stocks, please use 'ALL'. The 'OVERNIGHT' is not allowed.
  - Minimum version requirements: 9.2.4207)

    * The combination of ***start*** and ***end*** is as follows
        Start type|End type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 365 days before ***end***.
        str|None|***end*** is 365 days after ***start***.
        None|None|***end*** is the current date, ***start*** is 365 days before.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, historical candlestick data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
        <tr>
            <td>page_req_key</td>
            <td>bytes</td>
            <td>The key of the next page request.</td>
        </tr>
    </table>

    * Historical candlestick data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        time_key|str|Candlestick time.  (Format: yyyy-MM-dd HH:mm:ss
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        open|float|Open.
        close|float|Close.
        high|float|High.
        low|float|Low.
        pe_ratio|float|P/E ratio.  (This field is a ratio field, and % is not displayed.)
        turnover_rate|float|Turnover rate.
        volume|float|Volume.
        turnover|float|Turnover.
        change_rate|float|Change rate.
        last_close|float|Close of the previous K-line.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data, page_req_key = quote_ctx.request_history_kline('US.AAPL', start='2019-09-11', end='2019-09-18', max_count=5) # 5 per page, request the first page
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['close'].values.tolist()) # The closing price of the first page is converted to a list
else:
    print('error:', data)
while page_req_key != None: # Request all results after
    print('*************************************')
    ret, data, page_req_key = quote_ctx.request_history_kline('US.AAPL', start='2019-09-11', end='2019-09-18', max_count=5,page_req_key=page_req_key) # Request the page after turning data
    if ret == RET_OK:
        print(data)
    else:
        print('error:', data)
print('All pages are finished!')
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
code  name             time_key       open      close       high        low  pe_ratio  turnover_rate    volume      turnover  change_rate  last_close
0  US.AAPL   APPLE  2019-09-11 00:00:00  52.631194  53.963447  53.992409  52.549135    18.773        0.01039  177158584.0  9.808562e+09     3.179511   52.300545
..       ...   ...                  ...        ...        ...        ...        ...       ...            ...       ...           ...          ...         ...
4  US.AAPL   APPLE  2019-09-17 00:00:00  53.087346  53.265945  53.294907  52.884612    18.530        0.00432   73545872.0  4.046314e+09     0.363802   53.072865

[5 rows x 13 columns]
US.AAPL
[53.9634465, 53.84156475, 52.7953125, 53.072865, 53.265945]
*************************************
       code  name             time_key       open      close       high        low  pe_ratio  turnover_rate   volume      turnover  change_rate  last_close
0  US.AAPL   APPLE  2019-09-18 00:00:00  53.352831  53.76554  53.784847  52.961844    18.704        0.00602  102572372.0  5.682068e+09     0.937925   53.265945
All pages are finished!
```

:::tip Interface Restrictions
* Candlestick data with timeframes of **60 minutes and below**, is only supported for the last 8 years. **Daily** candlestick data is supported for the last 20 years. **Daily above** candlestick data is not restricted.
* We will issue historical candlestick quota based on your account assets and transaction conditions. Therefore, you can only obtain historical candlestick data for a limited number of stocks within 7 days. For specific rules, please refer to [Subscription Quota & Historical Candlestick Quota](../intro/authority.md#9123). The historical candlestick quota you consume on that day will be automatically released after 7 days.
* A maximum of 60 requests per 30 seconds. Note: If you obtain data by page, this frequency limit rule is only applicable to the first time calling the interface, and subsequent pages request frequency is unlimited.
* *Change rate*, only supports timeframes of daily and above.
* **Options** related candlestick data, only supports 1 day, 1 minute, 5 minutes, 15 minutes and 60 minutes.
* The pre-market, after-hours and overnight candlestick of US stocks, only supports timeframes of 60 minutes and below. Since the pre-market, after-hours and overnight session of the US stock market are irregular trading hours, the candlestick data for this period may be less than 2 years.
* *Turnover* of US stocks, only supports data after 2015-10-12.
:::

---

# Get Adjustment Factor

`get_rehab(code)`

* **Description**

    Get the stock adjustment factor

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, data for adjustment is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Data for adjustment format as follows: 
        Field|Type|Description
        :-|:-|:-
        ex_div_date|str|Ex-dividend date.
        split_base|float|Split numerator. (split_ratio= split numerator / split denominator)
        split_ert|float|Split dominator.
        join_base|float|Joint numerator. (split_ratio= joint numerator / joint denominator)
        join_ert|float|Joint dominator.
        split_ratio|float|Split ratio.  (- When 5 shares are joined into 1 share, the joint numerator = 5, the joint denominator  = 1, split_ratio = joint numerator / joint denominator= 5/1.- When 1 share is split into 5 shares, the split numerator =1, the split denominator =5, split_ratio= split numerator /split denominator =1/5.)
        per_cash_div|float|Dividend per share.
        bounce_base|float|Bounce numerator. (per_share_div_ratio= bounce numerator / bounce denominator)
        bounce_ert|float|Bounce dominator.
        per_share_div_ratio|float|Bounce ratio.  (- When the company has bonus shares and 1 share gives 5 shares, the bounce numerator = 1, the bounce denominator = 5, per_share_div_ratio = bounce numerator  / bounce denominator  = 1/5.)
        transfer_base|float|Conversion numerator. (per_share_trans_ratio= transfer_base / bounce denominator)
        transfer_ert|float|Conversion dominator.
        per_share_trans_ratio|float|Conversion ratio.  (- When 10 share is converted into 3 shares, the conversion numerator = 10, the conversion denominator = 3, per_share_trans_ratio = conversion numerator / conversion numerator = 10/3.)
        allot_base|float|Allotment numerator. (allotment ratio = allotment numerator / allotment denominator)
        allot_ert|float|Allotment dominator.
        allotment_ratio|float|Allotment ratio.  (- When 5 shares are allocated to 1 share, the allotment numerator = 5, the allotment denominator = 1, allotment_ratio = allotment numerator / allotment denominator = 5/1.)
        allotment_price|float|Issuance price.
        add_base|float|Additional issuance numerator. (stk_spo_ratio = additional issuance numerator / additional issuance denominator)
        add_ert|float|Additional issuance dominator.
        stk_spo_ratio|float|Additional issuance ratio.  (- When 1 additional share issues 5 shares, the additional issuance numerator = 1, the additional issuance denominator = 5, stk_spo_ratio = additional issuance numerator / additional issuance denominator = 1/5.)
        stk_spo_price|float|Additional issuance price.
        spin_off_base|float|Spin-off numerator.
        spin_off_ert|float|Spin-off dominator.
        spin_off_ratio|float|Spin-off ratio.
        forward_adj_factorA|float|Forward adjustment factor A.
        forward_adj_factorB|float|Forward adjustment factor B.
        backward_adj_factorA|float|Backward adjustment factor A.
        backward_adj_factorB|float|Backward adjustment factor B.


        Price after forward adjustment = price before forward adjustment * Forward adjustment factor A + Forward adjustment factor B  
        Price after backward adjustment = price before backward adjustment * Backward adjustment factor A + Backward adjustment factor B

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_rehab("HK.00700")
if ret == RET_OK:
    print(data)
    print(data['ex_div_date'][0]) # Take the first ex-dividend date
    print(data['ex_div_date'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    ex_div_date  split_ratio  per_cash_div  per_share_div_ratio  per_share_trans_ratio  allotment_ratio  allotment_price  stk_spo_ratio  stk_spo_price  spin_off_base      spin_off_ert     spin_off_ratio   forward_adj_factorA  forward_adj_factorB  backward_adj_factorA  backward_adj_factorB
0   2005-04-19          NaN          0.07                  NaN                    NaN              NaN              NaN            NaN            NaN          NaN       NaN       NaN        1.0                -0.07                   1.0                  0.07
..         ...          ...           ...                  ...                    ...              ...              ...            ...            ...                  ...                  ...                   ...                   ...
15  2019-05-17          NaN          1.00                  NaN                    NaN              NaN              NaN            NaN            NaN         NaN         NaN         NaN         1.0                -1.00                   1.0                  1.00

[16 rows x 16 columns]
2005-04-19
['2005-04-19', '2006-05-15', '2007-05-09', '2008-05-06', '2009-05-06', '2010-05-05', '2011-05-03', '2012-05-18', '2013-05-20', '2014-05-15', '2014-05-16', '2015-05-15', '2016-05-20', '2017-05-19', '2018-05-18', '2019-05-17']
```

:::tip Interface Limitations
* A maximum of 60 requests per 30 seconds
:::

---

# Get Earnings Price Move

`get_financials_earnings_price_move(code, period_count=None)`

* **Description**

    Get earnings price move

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    period_count|int|Number of earnings periods  (default 10, range [1, 50])

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns detailed data expanded by trading day</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Each row contains both earnings metadata and daily quote data:

        Field|Type|Description
        :-|:-|:-
        fiscal_year|int|Fiscal year  (e.g. 2024)
        financial_type|[F10Type](./quote.md#7667)|Report type  (0=Unknown, 1=Q1, 2=Q2, 3=Q3, 4=Q4, 7=Annual, 9=Quarterly, etc.)
        period_text|str|Earnings period  (e.g. "2024/Q3", "2024/FY")
        pub_trading_day_str|str|Earnings announcement trading day  (Format: yyyy-MM-dd; market timezone)
        pub_type|[EarningsPubTimeType](./quote.md#4958)|Announcement time type  (0=Unknown, 1=Pre-market, 2=After-market, 3=During-market)
        price_info_index|int|Index of the announcement day in itemList  (0-based; -1 if no data)
        day_offset|int|Trading day offset from announcement date  (negative=before, 0=announcement day, positive=after)
        trading_day_str|str|Trading date  (Format: yyyy-MM-dd; market timezone)
        close_price|float|Close price
        open_price|float|Open price
        highest_price|float|High price
        lowest_price|float|Low price
        last_close_price|float|Previous close price
        option_iv|float|Implied volatility  (Percentage value, e.g. 12.34 means 12.34%)
        option_hv|float|Historical volatility  (Percentage value, e.g. 12.34 means 12.34%)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_financials_earnings_price_move("HK.00700", period_count=2)
if ret == RET_OK:
    print(data)
    print(data['period_text'][0])
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
fiscal_year  financial_type  ... option_iv  option_hv
0          2026               1  ...    31.829     32.220
1          2026               1  ...    33.173     33.720
2          2026               1  ...    32.963     30.355
3          2026               1  ...       NaN        NaN
4          2025               4  ...    35.804     37.891
5          2025               4  ...    35.845     37.478
6          2025               4  ...    38.504     37.580
7          2025               4  ...    35.518     38.175
8          2025               4  ...    34.739     37.446
9          2025               4  ...    34.248     37.558
10         2025               4  ...    31.682     44.855
11         2025               4  ...    30.907     43.536
12         2025               4  ...    34.614     43.426
13         2025               4  ...    33.617     44.177
14         2025               4  ...    34.503     42.810

[15 rows x 17 columns]
2026/Q1
```

:::tip Restrictions
* Max 30 requests per 30 seconds.
* Supports HK, US, SG, JP, MY, and A-share equities only.
:::

---

# Get Earnings Price History

`get_financials_earnings_price_history(code)`

* **Description**

    Get earnings price history

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns price history data expanded by trading day</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Each row contains both earnings metadata and daily price data:

        Field|Type|Description
        :-|:-|:-
        fiscal_year|int|Fiscal year  (e.g. 2024)
        financial_type|[F10Type](./quote.md#7667)|Report type  (0=Unknown, 1=Q1, 2=Q2, 3=Q3, 4=Q4, 7=Annual, 9=Quarterly, etc.)
        period_text|str|Earnings period  (e.g. "2024/Q3", "2024/FY")
        is_current|bool|Whether the current time is within the earnings window period
        pub_trading_day|int|Earnings announcement trading day timestamp (seconds)
        pub_trading_day_str|str|Earnings announcement trading day  (Format: yyyy-MM-dd; market timezone)
        pub_time|int|Earnings actual release timestamp (seconds, includes time)
        pub_time_str|str|Earnings release datetime  (Format: yyyy-MM-dd HH:mm:ss; market timezone)
        pub_type|[EarningsPubTimeType](./quote.md#4958)|Announcement time type  (0=Unknown, 1=Pre-market, 2=After-market, 3=During-market)
        predict_vola_ratio_newest|float|Latest predicted volatility ratio  (Percentage value, e.g. 12.34 means 12.34%)
        predict_vola_ratio_highest|float|Highest predicted volatility ratio  (Percentage value, e.g. 12.34 means 12.34%)
        predict_vola_val_newest|float|Latest predicted volatility amount
        predict_vola_val_highest|float|Highest predicted volatility amount
        option_iv_crush|float|Option implied volatility crush  (Percentage value, e.g. 12.34 means 12.34%)
        option_strike_date_iv_crush|float|Strike date option IV crush  (Percentage value, e.g. 12.34 means 12.34%)
        trading_day|int|Trading day timestamp (seconds)
        trading_day_str|str|Trading date  (Format: yyyy-MM-dd; market timezone)
        close_price|float|Close price
        open_price|float|Open price
        highest_price|float|High price
        lowest_price|float|Low price
        last_close_price|float|Previous close price
        volume|float|Volume (shares)
        schedule_delta|int|Trading day offset from announcement date  (Negative=before announcement, 0=announcement day, positive=after announcement)
        schedule_close_price|float|Close price at the given day offset

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_financials_earnings_price_history("HK.00700")
if ret == RET_OK:
    print(data)
    print(data['period_text'][0])
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
fiscal_year  financial_type  ... schedule_delta  schedule_close_price
0           2026               1  ...            -15            504.000000
1           2026               1  ...            -14            495.200000
2           2026               1  ...            -13            493.400000
3           2026               1  ...            -12            478.600000
4           2026               1  ...            -11            473.800000
..           ...             ...  ...            ...                   ...
579         2021               2  ...             10            445.420633
580         2021               2  ...             11            438.045790
581         2021               2  ...             12            453.717332
582         2021               2  ...             13            463.396813
583         2021               2  ...             14            471.693512

[584 rows x 25 columns]
2026/Q1
```

:::tip Restrictions
* Max 30 requests per 30 seconds.
* Supports HK, US, SG, JP, MY, and A-share equities only.
:::

---

# Get Financial Statements

`get_financials_statements(code, statement_type=None, financial_type=None, currency_code=None, next_key=None, num=None)`

* **Description**

    Get financial statements (income/balance sheet/cash flow/key metrics) for a specified stock, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    statement_type|[FinancialStatementsType](./quote.md#6187)|Financial statement type  (0=Unknown, 1=Income(default), 2=BalanceSheet, 3=CashFlow, 4=MainIndex)
    financial_type|[F10Type](./quote.md#7667)|Report type  (0=All, 1=Q1, 2=Q2, 3=Q3, 4=Q4, 5=H1(Q1+Q2), 6=9M(Q1+Q2+Q3), 7=Annual, 9=Single-quarter combo, 10=Single-quarter+Annual(default), 11=Cumulative quarterly)
    currency_code|str|Currency code  (ISO 4217, e.g. CNY, USD, HKD, SGD, JPY, CAD, AUD; leave empty to return original currency data)
    next_key|str|Pagination key  (omit on first call, pass the returned next_key for subsequent pages; "-1" means no more data)
    num|int|Records per page  (default 10, range 1~50)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns financial statements data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        structure_list|list|Field structure list
        report_list|list|Financial report list
        next_key|str|Pagination key  ("-1" means no more data)

    * Each entry in structure_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        field_id|int|Financial field ID
        display_name|str|Field display name  (e.g. "Revenue"; current language)

    * Each entry in report_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        date_time|int|Report end date timestamp (seconds)
        date_time_str|str|Report end date string  (Format: YYYY-MM-DD; market timezone)
        fiscal_year|int|Fiscal year  (e.g. 2024)
        financial_type|[F10Type](./quote.md#7667)|Report type  (0=Unknown, pass as-is for next request)
        period_text|str|Reporting period  (e.g. "2024/Q3", "2024/FY")
        item_list|list|Financial data item list
        currency_info|str|Currency display name  (e.g. "RMB", "USD")
        accounting_standards|str|Accounting standard  (e.g. "IFRS")
        auditor_report|str|Auditor opinion  (e.g. "Unqualified")
        currency_code|str|Currency code  (ISO 4217, e.g. "CNY", "USD")

    * Each entry in item_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        field_id|int|Financial field ID
        data|float|Financial value
        yoy|float|Year-over-year  (value before the % sign, e.g. 13.86 means 13.86%; absent when no YoY data)
        qoq|float|Quarter-over-quarter  (value before the % sign, e.g. 1.23 means 1.23%; absent when no QoQ data)
        display_name|str|Field display name  (matches the display_name of the corresponding entry in structure_list)

* **Example**

```python
import pandas as pd
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_financials_statements("HK.00700")
if ret == RET_OK:
    df = pd.DataFrame(data['report_list'][0]['item_list'])
    print(df)
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
field_id                       display_name          data         yoy
0       5001                      Total Revenue  7.517660e+11   13.859603
1       5002                  Operating Revenue  7.517660e+11   13.859603
2       5005                    Cost of Revenue -3.291730e+11   -5.839665
3       5008                 Cost of Goods Sold -3.291730e+11   -5.839665
4       5010                       Gross Profit  4.225930e+11   21.001529
5       5013                  Operating Expense -1.778540e+11  -19.245855
6       5015                   Selling Expenses -4.172700e+10  -14.672419
7       5016            Administrative Expenses -1.361270e+11  -20.721703
8       5032  Special Items of Operating Income -3.177000e+09 -139.702574
9       5034                   Operating Profit  2.415620e+11   16.080327
10      5035                   Financing Income  1.690900e+10    5.654836
11      5036                     Financing Cost -1.513000e+10  -26.283282
12      5037     Share of Profits of Associates  2.374000e+10   -5.703845
13      5040                      Pretax Profit  2.772490e+11   14.810030
14      5041     Special Items of Pretax Income  1.016800e+10  142.846907
15      5043                                Tax -4.744800e+10   -5.397841
16      5045                         Net Profit  2.298010e+11   16.966717
17      5046  Profit from Continuing Operations  2.298010e+11   16.966717
18      5050                 Minority Interests  4.959000e+09  107.142857
19      5051       Net Income to Parent Company  2.248420e+11   15.854343
20      5052  Net Income to Common Stockholders  2.248420e+11   15.854343
21      5054                          Basic EPS  2.474900e+01   18.201356
22      5055                        Diluted EPS  2.415300e+01   17.900029
```

:::tip Interface Limit
* Up to 30 requests per 30 seconds.
* Supports stocks and funds.
:::

---

# Get Revenue Breakdown

`get_financials_revenue_breakdown(code, date=None, financial_type=None, currency_code=None)`

* **Description**

    Get revenue breakdown data for a specified stock, supporting multi-dimensional breakdown by product, industry, region, and business

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    date|int|Filter timestamp  (seconds; pass a date value from the returned screen_date_list to query historical data; omit or pass 0 to return the latest period)
    financial_type|[F10Type](./quote.md#7667)|Report type  (0=All, 1=Q1, 2=Q2, 3=Q3, 4=Q4, 5=H1, 6=9M, 7=Annual, 9=Single-quarter combo; default 0=All)
    currency_code|str|Currency code  (ISO 4217, e.g. CNY, USD, HKD, SGD, JPY, CAD, AUD; leave empty to return original currency data)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns revenue breakdown data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        period|str|Reporting period  (e.g. "2025/FY", "2024/H1")
        breakdown_list|list|Revenue breakdown list  (each entry contains type and item_list)
        currency_code|str|Currency code  (ISO 4217)
        screen_date_list|list|Available historical dates  (only returned when both date and financial_type are not set)

    * Each entry in breakdown_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        type|[RevenueBreakdownType](./quote.md#7)|Dimension type  (1=Product, 2=Industry, 4=Region, 8=Business)
        item_list|list|Revenue breakdown items  (each entry contains name, main_oper_income, ratio)

    * Each entry in item_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        name|str|Item name
        main_oper_income|float|Operating revenue
        ratio|float|Ratio  (value before %, e.g. 12.34 means 12.34%)

    * Each entry in screen_date_list contains the following fields:

        Field|Type|Description
        :-|:-|:-
        date|int|Filter timestamp  (seconds; pass-back type, must be a value from this list)
        period_text|str|Reporting period  (e.g. "2025/FY")
        financial_type|[F10Type](./quote.md#7667)|Report type

* **Example**

```python
import pandas as pd
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_financials_revenue_breakdown("HK.00700")
if ret == RET_OK:
    df = pd.DataFrame(data['breakdown_list'][0]['item_list'])
    print(df)
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
name  main_oper_income    ratio
0                         Value-added services      3.692810e+11  49.1218
1  Financial technology and corporate services      2.294350e+11  30.5194
2                            Marketing service      1.449730e+11  19.2843
3                                        Other      8.077000e+09   1.0744
```

:::tip Interface Limit
* Up to 30 requests per 30 seconds.
* Supports stocks and funds.
:::

---

# Get Research Analyst Consensus

`get_research_analyst_consensus(code)`

* **Description**

    Get the analyst consensus rating, target price range and rating distribution for the specified stock over the past 3 months

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, returns analyst consensus data dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dict contains the following fields:

        Field|Type|Description
        :-|:-|:-
        highest|float|Highest target price
        average|float|Average target price
        lowest|float|Lowest target price
        rating|[ResearchRatingType](./quote.md#8002)|Consensus rating  (Analyst consensus rating over the past 3 months
0=Unknown, 1=Sell, 2=Underperform, 3=Hold, 4=Buy, 5=StrongBuy
US stocks only return Sell(1)/Hold(3)/Buy(4); non-US markets also support Underperform(2)/StrongBuy(5))
        total|int|Total analyst count  (Total number of analysts who submitted ratings in the past 3 months)
        update_time|int|Update timestamp  (Seconds; timestamp of when rating data was updated)
        update_time_str|str|Update date  (Format YYYY-MM-DD, in the market's timezone)
        buy|float|Buy rating ratio  (Value before the percent sign, e.g. 12.34 means 12.34%)
        hold|float|Hold rating ratio  (Value before the percent sign, e.g. 12.34 means 12.34%)
        sell|float|Sell rating ratio  (Value before the percent sign, e.g. 12.34 means 12.34%)
        strong_buy|float|Strong Buy ratio  (Value before the percent sign, e.g. 12.34 means 12.34%; non-US markets only)
        underperform|float|Underperform ratio  (Value before the percent sign, e.g. 12.34 means 12.34%; non-US markets only)

* **Example**

```python
import json
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_research_analyst_consensus("HK.00700")
if ret == RET_OK:
    print(json.dumps(data, indent=2, ensure_ascii=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
{
  "highest": 820.0,
  "average": 716.0,
  "lowest": 579.51,
  "rating": 5,
  "total": 44,
  "update_time": 1778469178,
  "update_time_str": "2026-05-11",
  "buy": 22.727,
  "hold": 0.0,
  "sell": 0.0,
  "strong_buy": 77.273,
  "underperform": 0.0
}
```

:::tip API Limitations
* Maximum 30 requests per 30 seconds.
* Supports common stocks and REITs.
:::

---

# Get Research Rating Summary

`get_research_rating_summary(code, rating_dimension_type=None, uid=None, num=None, next_key=None)`

* **Description**

    Get the institution or analyst rating summary list for the specified stock, or the rating detail for a specified institution/analyst, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    rating_dimension_type|[ResearchRatingDimensionType](./quote.md#9207)|Rating dimension  (0=Unknown, 1=Institution, 2=Analyst; default is Institution)
    uid|str|Institution or analyst UID  (Empty=get rating summary list for the stock
non-empty=get rating detail for the specified uid (analyst uid must be used with rating_dimension_type=2))
    num|int|Number of items per page  (Default 10, range 1~20)
    next_key|str|Pagination key  (Leave empty on first request; pass the next_key returned from the previous response to continue; "-1" means no more data)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, returns rating summary data dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dict contains the following fields:

        Field|Type|Description
        :-|:-|:-
        inst_rating_summary_list|list|Institution rating summary list  (Populated when uid is empty and rating_dimension_type=1
each item contains institution_info and rating_item_list)
        analyst_rating_summary_list|list|Analyst rating summary list  (Populated when uid is empty and rating_dimension_type=2
each item contains analyst_info and rating_item_list)
        inst_rating_detail|dict|Institution rating detail  (Populated when uid is non-empty and rating_dimension_type=1
contains institution_info, analyst_info_list, and rating_item_list)
        analyst_rating_detail|dict|Analyst rating detail  (Populated when uid is non-empty and rating_dimension_type=2
contains analyst_info and rating_item_list)
        next_key|str|Pagination key  ("-1" means no more data)

    * Fields in each item of inst_rating_summary_list (institution rating summary row):

        Field|Type|Description
        :-|:-|:-
        institution_info|dict|Institution info, see table below
        rating_item_list|list|Rating record list, see table below

    * institution_info fields (InstInfo):

        Field|Type|Description
        :-|:-|:-
        institution_uid|str|Institution unique identifier
        institution_picture_url|str|Institution picture URL
        institution_name|str|Institution name
        update_time|int|Update timestamp  (Seconds, in market timezone)
        update_time_str|str|Update date  (Format YYYY-MM-DD, in market timezone)
        institution_source_name|str|Institution source name
        institution_en_name|str|Institution English name

    * analyst_info fields (AnalystInfo):

        Field|Type|Description
        :-|:-|:-
        analyst_uid|str|Analyst unique identifier
        analyst_name|str|Analyst name
        analyst_picture_url|str|Analyst avatar URL
        num_of_stars|float|Star rating  (0.0~5.0, e.g. 3.50 means 3.5 stars)
        success_rate|float|Success rate  (Value before the percent sign, e.g. 12.34 means 12.34%)
        excess_return|float|Excess return  (Value before the percent sign, e.g. 12.34 means 12.34%)
        stock_success_rate|float|Stock success rate  (Value before the percent sign, e.g. 12.34 means 12.34%)
        stock_avg_return|float|Stock average return  (Value before the percent sign, e.g. 12.34 means 12.34%)
        institution_info|dict|Affiliated institution info, see institution_info field table
        update_time|int|Update timestamp  (Seconds, in market timezone)
        update_time_str|str|Update date  (Format YYYY-MM-DD, in market timezone)

    * Fields in each item of rating_item_list (RatingItem):

        Field|Type|Description
        :-|:-|:-
        analyst_uid|str|Analyst unique identifier
        institution_uid|str|Institution unique identifier
        rating|[ResearchRatingType](./quote.md#8002)|Rating  (0=Unknown, 1=Sell, 2=Underperform, 3=Hold, 4=Buy, 5=StrongBuy
this API only returns Sell(1)/Hold(3)/Buy(4), higher value means higher rating)
        target_price|float|Target price
        recommendation_date|int|Rating date timestamp  (Seconds, in market timezone)
        recommendation_date_str|str|Rating date  (Format YYYY-MM-DD, in market timezone)
        rating_url|str|Rating source URL
        update_time|int|Update timestamp  (Seconds, in market timezone)
        update_time_str|str|Update date  (Format YYYY-MM-DD, in market timezone)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_research_rating_summary("US.AAPL", rating_dimension_type=1)
if ret == RET_OK:
    rows = []
    for row in data.get('inst_rating_summary_list', []):
        info = row.get('institution_info', {})
        rows.append({
            'institution_name':        info.get('institution_name', ''),
            'institution_en_name':     info.get('institution_en_name', ''),
            'institution_uid':         info.get('institution_uid', ''),
            'institution_source_name': info.get('institution_source_name', ''),
            'update_time_str':         info.get('update_time_str', ''),
        })
    df = pd.DataFrame(rows)
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
institution_name institution_en_name                      institution_uid    institution_source_name update_time_str
           Wedbush             Wedbush 8c9ae25a-07e2-4d52-a511-b0dd115a5224                    Wedbush      2024-03-01
          Evercore            Evercore a746f081-c12a-4d6d-8067-f4b6634de478               Evercore ISI      2024-03-21
               UBS                 UBS 1d3bfc25-1dda-48fd-bd9f-d4de47e68def                        UBS      2024-03-01
     Goldman Sachs       Goldman Sachs d0e296b4-c2e4-4fad-837c-cd79aaed2e8e              Goldman Sachs      2024-03-01
         Bernstein           Bernstein 16358c98-ccc1-4d08-a875-2c727b7b8d70                  Bernstein      2024-03-01
               DBS                 DBS 44dec2a6-aca9-4b52-9fed-4bbf78749783                        DBS      2024-03-01
   BofA Securities     BofA Securities 7890753d-5482-4311-a7af-8d5feed39f3e Bank of America Securities      2024-03-01
Phillip Securities  Phillip Securities a294f0ca-10c0-4884-86a7-359995505e70         Phillip Securities      2024-09-09
       J.P. Morgan         J.P. Morgan f5ec822c-d561-4db3-a09d-a1e71a9a832f                J.P. Morgan      2024-03-01
    Morgan Stanley      Morgan Stanley 9a29ac93-221c-4c1a-ba1a-bbbbf57a5ca6             Morgan Stanley      2024-03-01
```

:::tip API Limits
* Maximum 30 requests per 30 seconds.
* Supports US stocks and REITs.
:::

---

# Get Morningstar Research Report

`get_research_morningstar_report(code)`

* **Description**

    Get the Morningstar research report for the specified stock, including star rating, fair value, economic moat, uncertainty, financial health, capital allocation, bull/bear arguments, and analyst notes

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, returns Morningstar research report data dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dict contains the following fields:

        Field|Type|Description
        :-|:-|:-
        rating_type|[MorningstarRatingType](./quote.md#3877)|Rating type  (0=Unknown, 1=Quantitative (system model), 2=Qualitative (analyst manual))
        star_rating|int|Morningstar star rating  (Value 1~5 stars)
        star_update_time|int|Star rating update timestamp  (Seconds, in market timezone)
        star_update_time_str|str|Star rating update date  (Format YYYY-MM-DD, in market timezone)
        fair_value|float|Fair value
        fair_value_content|dict|Fair value analysis, see StringWithUpdateTime field table
        economic_moat_label|str|Economic moat rating  (e.g. Wide, Narrow, None)
        economic_moat_content|dict|Economic moat analysis, see StringWithUpdateTime field table
        uncertainty_label|str|Uncertainty rating  (e.g. Low, Medium, High, Very High, Extreme)
        uncertainty_content|dict|Uncertainty analysis, see StringWithUpdateTime field table
        financial_health_label|str|Financial health rating
        financial_health_content|dict|Financial health analysis, see StringWithUpdateTime field table
        analyst_report_by_line|list|Analyst byline list  (e.g. ["William Kerwin, CFA"])
        analyst_report_update_time|int|Analyst report update timestamp  (Seconds, in market timezone)
        analyst_report_update_time_str|str|Analyst report update date  (Format YYYY-MM-DD, in market timezone)
        bull_say|list|Bull arguments list, each item see StringWithUpdateTime field table
        bear_say|list|Bear arguments list, each item see StringWithUpdateTime field table
        capital_allocation_label|str|Capital allocation rating
        capital_allocation_content|dict|Capital allocation analysis, see StringWithUpdateTime field table
        analyst_note_title|dict|Analyst note title, see StringWithUpdateTime field table
        analyst_note_content|dict|Analyst note content, see StringWithUpdateTime field table
        investment_thesis_content|dict|Investment thesis, see StringWithUpdateTime field table
        fundamentals_content|dict|Fundamentals report, see StringWithUpdateTime field table
        valuation_content|dict|Valuation report, see StringWithUpdateTime field table
        pdf_url|str|PDF report download URL

    * StringWithUpdateTime fields (nested text structure):

        Field|Type|Description
        :-|:-|:-
        context|str|Text content
        update_time|int|Update timestamp  (Seconds, in market timezone)
        update_time_str|str|Update date  (Format YYYY-MM-DD, in market timezone)

* **Example**

```python
import json
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_research_morningstar_report("HK.00700")
if ret == RET_OK:
    print(json.dumps(data, indent=2, ensure_ascii=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
{
  "rating_type": 2,
  "star_rating": 4,
  "star_update_time": 1778257800,
  "star_update_time_str": "2026-05-09",
  "fair_value": 800.0,
  "fair_value_content": {
    "context": "Our fair value estimate for Tencent is HKD 800 per share. About 85% of our valuation comes from Tencent’s core business, while ...
    "update_time": 1755138060,
    "update_time_str": "2025-08-14"
  },
  "economic_moat_label": "Wide",
  "economic_moat_content": {
    "context": "Tencent's wide moat is primarily based on network effects around its massive user base. In addition, Tencent possesses ...
    "update_time": 1766457150,
    "update_time_str": "2025-12-23"
  },
  "uncertainty_label": "High",
  "uncertainty_content": {
    "context": "Our Morningstar Uncertainty Rating for Tencent is High due to regulatory risks and competitive intensity across...
    "update_time": 1766457180,
    "update_time_str": "2025-12-23"
  },
  //...
}
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* Supports common stocks and REITs.
:::

---

# Get Valuation Detail

`get_valuation_detail(code, valuation_type=None, interval_type=None)`

* **Description**

    Get valuation detail for the specified stock or index, including valuation trend, market distribution, sector distribution (stocks only), and earnings/revenue growth rate (stocks only, not available for PB)

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    valuation_type|[ValuationType](./quote.md#3419)|Valuation type  (0=Unknown (use recommended type), 1=PE (Price-to-Earnings), 2=PB (Price-to-Book), 3=PS (Price-to-Sales); default None (use recommended type))
    interval_type|[ValuationIntervalType](./quote.md#2834)|Historical data time interval  (0=Unknown, 1=Month3, 2=Month6, 3=Year1, 4=Year3, 5=Since2019, 6=Year5, 7=Year10, 8=Year2, 9=Year20, 10=Year30; default None)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, returns valuation detail data dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dict contains the following fields:

        Field|Type|Description
        :-|:-|:-
        valuation_type|[ValuationType](./quote.md#3419)|Actual valuation type  (0=Unknown, 1=PE, 2=PB, 3=PS)
        last_update_time|int|Last update timestamp  (Seconds, in market timezone)
        last_update_time_str|str|Last update time  (Format YYYY-MM-DD HH:MM:SS, in market timezone)
        trend|dict|Valuation trend data, see trend field table
        market_distribution|dict|Market distribution data, see market_distribution field table
        plate_distribution|dict|Sector distribution data, see plate_distribution field table  (Stocks only)
        profit_growth_rate|dict|Earnings/revenue growth rate data, see profit_growth_rate field table  (Stocks only; not available for PB valuation type)

    * trend fields (valuation trend summary):

        Field|Type|Description
        :-|:-|:-
        current_value|float|Current valuation
        average_value|float|Historical average valuation
        avg_minus_1_stddev|float|Historical average - 1σ
        avg_plus_1_stddev|float|Historical average + 1σ
        valuation_percentile|float|Historical percentile  (Value before %, e.g. 12.34 means 12.34%)
        forward_value|float|Forward valuation  (PE / PS only)
        historical_items|list|Historical valuation list, each item see historical_items field table

    * historical_items fields (historical valuation entry):

        Field|Type|Description
        :-|:-|:-
        value|float|Valuation
        time|int|Timestamp  (Seconds, in market timezone)
        time_str|str|Date  (Format YYYY-MM-DD, in market timezone)
        plate_value|float|Sector average valuation

    * market_distribution fields (market / constituent stock distribution):

        Field|Type|Description
        :-|:-|:-
        sections|list|Distribution sections list (descending), each item see sections field table
        total|int|Total market count / constituent stock count
        ranking|int|Stock's valuation ranking in the market  (Not available for indexes)
        average_value|float|Market average valuation  (Not available for indexes)
        median_value|float|Market median valuation  (Not available for indexes)

    * sections fields (distribution section entry):

        Field|Type|Description
        :-|:-|:-
        start|float|Section start value
        end|float|Section end value  (0 means no upper limit)
        number|int|Number of stocks in this section

    * plate_distribution fields (sector distribution, stocks only):

        Field|Type|Description
        :-|:-|:-
        plate|str|Sector code
        plate_name|str|Sector name
        plate_average_value|float|Sector average valuation
        plate_ranking|int|Stock's valuation ranking within the sector
        plate_stock_item_count|int|Total stocks in the sector
        stock_items|list|Sector constituent stock valuation details, each item see stock_items field table

    * stock_items fields (sector constituent stock entry):

        Field|Type|Description
        :-|:-|:-
        security|str|Stock code
        name|str|Stock name
        value|float|Valuation
        market_cap|float|Market cap

    * profit_growth_rate fields (earnings/revenue growth rate, stocks only, not PB):

        Field|Type|Description
        :-|:-|:-
        financial_ttm_multiple|float|TTM growth multiple
        market_cap_multiple|float|Market cap growth multiple
        year_count|int|Number of years used to calculate growth multiple
        profit_data|list|Per-period data list, each item see profit_data field table
        conclusion_detailed|str|Valuation conclusion description

    * profit_data fields (per-period earnings/revenue entry):

        Field|Type|Description
        :-|:-|:-
        financial_year|int|Financial report year
        financial_quarter|int|Financial report quarter  (1=Q1, 2=Q2, 3=Q3, 4=FY)
        period_str|str|Financial report period  (e.g. "2024/Q3", "2024/FY")
        report_date|int|Report date timestamp  (Seconds, in market timezone)
        report_date_str|str|Report date  (Format YYYY-MM-DD, in market timezone)
        market_cap_multiple|float|Market cap multiple on report date  (Base period = 1)
        finance_data_multiple|float|Earnings/revenue multiple  (Base period = 1; depends on valuation_type)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_valuation_detail("HK.00700")
if ret == RET_OK:
    trend = data.get('trend', {})
    items = trend.get('historical_items', [])
    df = pd.DataFrame(items)
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
value       time   time_str  plate_value
22.690 1746979200 2025-05-12       22.678
22.186 1747065600 2025-05-13       22.179
22.843 1747152000 2025-05-14       22.817
22.046 1747238400 2025-05-15       22.050
21.538 1747324800 2025-05-16       21.577
21.792 1747584000 2025-05-19       21.821
//...
18.087 1776960000 2026-04-24       18.147
17.544 1777219200 2026-04-27       17.617
17.368 1777305600 2026-04-28       17.444
17.566 1777392000 2026-04-29       17.650
17.148 1777478400 2026-04-30       17.227
17.339 1777824000 2026-05-04       17.421
17.310 1777910400 2026-05-05       17.393
16.972 1777996800 2026-05-06       17.059
17.500 1778083200 2026-05-07       17.589
17.266 1778169600 2026-05-08       17.364
17.039 1778428800 2026-05-11       17.143
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* Supports common stocks, funds, and indexes.
* PB valuation type does not include earnings/revenue growth rate module.
* Indexes do not include ranking, average value, or median value.
:::

---

# Get Valuation Plate Stock List

`get_valuation_plate_stock_list(code, valuation_type=None, next_key=None, num=None, sort_type=None, sort_id=None, filter_security=None)`

* **Description**

    Get the valuation list of constituent stocks for a board or index, including valuation, forward valuation, historical percentile, and market cap; the first full request for an index also returns the associated board list

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Board or index code  (e.g. HK.LIST23363 (board) or HK.800000 (index); individual stocks are not supported)
    valuation_type|[ValuationType](./quote.md#3419)|Valuation type  (0=Unknown, 1=PE, 2=PB, 3=PS; default None (1=PE))
    next_key|str|Pagination key  (Omit on first request; pass the nextKey from the previous response on subsequent requests; "-1" means no more data)
    num|int|Page size  (Default 10, range 1–50)
    sort_type|[SortType](./quote.md#7778)|Sort direction  (1=Desc, 2=Asc; default None (ascending))
    sort_id|[SortField](./quote.md#5823)|Sort column  (51=MarketCap (default), 52=Valuation, 53=ForwardValuation, 54=HistoricalPercentile)
    filter_security|str|Board filter  (Valid for indexes only; filter constituent stocks by board, e.g. HK.LIST23363; no filter if omitted)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns a dict of constituent stock valuation data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns an error description</td>
        </tr>
    </table>

    * The returned dict contains the following fields:

        Field|Type|Description
        :-|:-|:-
        count|int|Total constituent stock count
        stock_list|list|Constituent stock valuation list; each item see stock_list field table
        next_key|str|Pagination key  ("-1" means no more data)
        plate_list|list|Associated board list  (Returned only on the first full request when target is an index; each item see plate_list field table)

    * stock_list fields (constituent stock valuation entry):

        Field|Type|Description
        :-|:-|:-
        symbol|str|Stock code
        valuation_val|float|Valuation
        forward_value|float|Forward valuation  (Currently supports PE and PS only)
        valuation_percentile|float|Historical percentile  (Value before %, e.g. 12.34 means 12.34%)
        market_cap|float|Market cap
        name|str|Stock name

    * plate_list fields (index board entry):

        Field|Type|Description
        :-|:-|:-
        symbol|str|Board code
        name|str|Board name

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_valuation_plate_stock_list("HK.LIST23363")
if ret == RET_OK:
    df = pd.DataFrame(data.get('stock_list', []))
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
symbol            name  valuation_val  valuation_percentile   market_cap
HK.08076        SING LEE         -2.300             65.337673 3.029652e+07
HK.08092    ITE HOLDINGS         19.500             98.209927 3.609481e+07
HK.08036   EBROKER GROUP        -12.000             35.313263 4.428000e+07
HK.01561 PAN ASIA DATA H        -23.500              1.057770 5.007634e+07
HK.08071   CH NETCOMTECH        -13.000             31.489015 6.091863e+07
HK.00248  HKC INT'L HOLD         -2.056             19.446705 6.771489e+07
HK.01613       SYNERTONE         -2.796             72.660700 8.841764e+07
HK.08062   EFT SOLUTIONS        -93.333              0.244101 1.344000e+08
HK.01949      PLATT NERA         -5.147             36.523929 1.344000e+08
HK.01206     TECHNOVATOR         -0.314             41.171684 1.720823e+08
```

:::tip API Limits
* Up to 30 requests per 30 seconds.
* Supports boards and indexes; individual stocks are not supported.
* For indexes, the first full request additionally returns the associated board list (plate_list).
:::

---

# Get Corporate Actions - Dividends

`get_corporate_actions_dividends(code)`

* **Description**

    Get dividend history records for a stock

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports stocks and funds)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dividend data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        dividend_list|list|Dividend list  (sorted by announcement date in descending order; see dividend_list field table for each item)

    * dividend_list fields (dividend entry):

        Field|Type|Description
        :-|:-|:-
        pub_date|str|Announcement date  (format YYYY/MM/DD, in the market's timezone)
        statement|str|Distribution plan  (e.g. "Final dividend HKD 5.3")
        process|str|Event status  (e.g. "Implemented" / "Proposed"; only available for HK and A-share common stocks and trusts)
        record_date|str|Record date  (format YYYY/MM/DD, in the market's timezone. Not available for ETFs)
        ex_date|str|Ex-dividend date  (format YYYY/MM/DD, in the market's timezone)
        dividend_payable_date|str|Payment date  (format YYYY/MM/DD, in the market's timezone)
        fiscal_year|str|Fiscal year  (e.g. "2026"; only for ETFs)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_corporate_actions_dividends("HK.00700")
if ret == RET_OK:
    df = pd.DataFrame(data.get('dividend_list', []))
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
pub_date                                                                      statement        process record_date    ex_date dividend_payable_date
03/18/2026                                           Cash Dividend: 5.30000 HKD Per Share           Plan  05/18/2026 05/15/2026            06/01/2026
03/19/2025                                           Cash Dividend: 4.50000 HKD Per Share Implementation  05/19/2025 05/16/2025            05/30/2025
03/20/2024                                           Cash Dividend: 3.40000 HKD Per Share Implementation  05/20/2024 05/17/2024            05/31/2024
03/22/2023                                           Cash Dividend: 2.40000 HKD Per Share Implementation  05/22/2023 05/19/2023            06/05/2023
11/16/2022 Distribution in Specie: 1.00000 MEITUAN-W Share for Every 10.00000 Shares Held Implementation  01/06/2023 01/05/2023            03/24/2023
03/23/2022                                           Cash Dividend: 1.60000 HKD Per Share Implementation  05/23/2022 05/20/2022            06/06/2022
12/23/2021     Distribution in Specie: 1.00000 JD-SW Share for Every 21.00000 Shares Held Implementation  01/21/2022 01/20/2022            03/25/2022
03/24/2021                                           Cash Dividend: 1.60000 HKD Per Share Implementation  05/25/2021 05/24/2021            06/07/2021
03/18/2020                                           Cash Dividend: 1.20000 HKD Per Share Implementation  05/18/2020 05/15/2020            05/29/2020
03/21/2019                                           Cash Dividend: 1.00000 HKD Per Share Implementation  05/20/2019 05/17/2019            05/31/2019
12/03/2018  Distribution in Specie: 1.00000 TME-SW Share for Every 3900.00000 Shares Held Implementation  01/02/2019 12/28/2018            02/20/2019
03/21/2018                                           Cash Dividend: 0.88000 HKD Per Share Implementation  05/21/2018 05/18/2018            06/01/2018
06/30/2017         Rights Issue: 1.00000 CHINA LIT Share for Every 1256.00000 Shares Held Implementation  10/19/2017 10/18/2017            11/07/2017
03/22/2017                                           Cash Dividend: 0.61000 HKD Per Share Implementation  05/22/2017 05/19/2017            06/02/2017
03/17/2016                                           Cash Dividend: 0.47000 HKD Per Share Implementation  05/23/2016 05/20/2016            06/02/2016
03/18/2015                                           Cash Dividend: 0.36000 HKD Per Share Implementation  05/18/2015 05/15/2015            05/29/2015
03/19/2014                                           Cash Dividend: 0.24000 HKD Per Share Implementation  05/19/2014 05/16/2014            05/30/2014
03/20/2013                                           Cash Dividend: 1.00000 HKD Per Share Implementation  05/21/2013 05/20/2013            05/30/2013
03/14/2012                                           Cash Dividend: 0.75000 HKD Per Share Implementation  05/21/2012 05/18/2012            05/30/2012
03/16/2011                                           Cash Dividend: 0.55000 HKD Per Share Implementation  05/04/2011 05/03/2011            05/25/2011
03/17/2010                                           Cash Dividend: 0.40000 HKD Per Share Implementation  05/06/2010 05/05/2010            05/26/2010
03/18/2009   Cash Dividend: 0.25000 HKD Per Share,Special Dividend: 0.10000 HKD Per Share Implementation  05/07/2009 05/06/2009            05/27/2009
03/19/2008                                           Cash Dividend: 0.16000 HKD Per Share Implementation  05/07/2008 05/06/2008            05/28/2008
03/21/2007                                           Cash Dividend: 0.12000 HKD Per Share Implementation  05/10/2007 05/09/2007            05/30/2007
03/22/2006                                           Cash Dividend: 0.08000 HKD Per Share Implementation  05/16/2006 05/15/2006            06/07/2006
03/17/2005                                           Cash Dividend: 0.07000 HKD Per Share Implementation  04/20/2005 04/19/2005            05/17/2005
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
* Supports stocks and funds.
:::

---

﻿# Get Corporate Actions - Buybacks

`get_corporate_actions_buybacks(code, next_key=None, num=None)`

* **Description**

    Get buyback records for a stock (HK stocks / A-shares, supports pagination)

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports HK stocks, A-share stocks and funds)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key returned from the previous request to continue; "-1" means no more data)
    num|int|Page size  (Number of records per page, default 10, range 1~50)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns buyback data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" means no more data; pass this value as next_key in the next request to continue)
        hk_buy_back_list|pd.DataFrame|HK buyback list  (See hk_buy_back_list field table for each item; empty for A-share stocks)
        a_buy_back_list|pd.DataFrame|A-share buyback list  (See a_buy_back_list field table for each item; empty for HK stocks)

    * hk_buy_back_list fields (HK buyback entry):

        Field|Type|Description
        :-|:-|:-
        publ_date|int|Announcement date timestamp  (Unix timestamp (seconds), in the market's timezone)
        publ_date_str|str|Announcement date  (Format YYYY-MM-DD, in the market's timezone)
        end_date|int|Buyback end date timestamp  (Unix timestamp (seconds), in the market's timezone)
        end_date_str|str|Buyback end date  (Format YYYY-MM-DD, in the market's timezone)
        buy_back_money|float|Buyback amount
        buy_back_sum|int|Buyback shares  (Unit: shares)
        percentage|float|Percentage of issued shares  (Value before the percent sign, e.g. 12.34 means 12.34%)
        high_price|float|Highest buyback price
        low_price|float|Lowest buyback price
        cumulative_sum|int|Cumulative buyback shares this round  (Unit: shares)
        cumulative_percentage|float|Cumulative percentage of total shares this round  (Value before the percent sign, e.g. 12.34 means 12.34%)
        share_type|str|Share type

    * a_buy_back_list fields (A-share buyback entry):

        Field|Type|Description
        :-|:-|:-
        change_reg_date|int|Business registration change date timestamp  (Unix timestamp (seconds), in the market's timezone)
        change_reg_date_str|str|Business registration change date  (Format YYYY-MM-DD, in the market's timezone)
        change_date|int|Share change date timestamp  (Unix timestamp (seconds), in the market's timezone)
        change_date_str|str|Share change date  (Format YYYY-MM-DD, in the market's timezone)
        event_proce_desc|str|Event process description
        advance_date|int|Proposal announcement date timestamp  (Unix timestamp (seconds), in the market's timezone)
        advance_date_str|str|Proposal announcement date  (Format YYYY-MM-DD, in the market's timezone)
        meet_pass_date|int|Shareholder meeting approval date timestamp  (Unix timestamp (seconds), in the market's timezone)
        meet_pass_date_str|str|Shareholder meeting approval date  (Format YYYY-MM-DD, in the market's timezone)
        start_date|int|Buyback start date timestamp  (Unix timestamp (seconds), in the market's timezone)
        start_date_str|str|Buyback start date  (Format YYYY-MM-DD, in the market's timezone)
        end_date|int|Buyback end date timestamp  (Unix timestamp (seconds), in the market's timezone)
        end_date_str|str|Buyback end date  (Format YYYY-MM-DD, in the market's timezone)
        pay_date|int|Payment date timestamp  (Unix timestamp (seconds), in the market's timezone)
        pay_date_str|str|Payment date  (Format YYYY-MM-DD, in the market's timezone)
        seller|str|Seller  (The party whose shares are being bought back)
        buy_back_mode|str|Buyback method
        share_type|str|Share type
        buy_back_sum|int|Buyback shares  (Unit: shares)
        buy_back_money|float|Buyback amount
        percentage|float|Percentage of issued shares  (Value before the percent sign, e.g. 12.34 means 12.34%)
        value_floor|float|Minimum planned buyback amount
        value_ceiling|float|Maximum planned buyback amount
        price_floor|float|Minimum buyback price
        price_ceiling|float|Maximum buyback price
        volume_floor|float|Minimum planned buyback shares
        volume_ceiling|float|Maximum planned buyback shares

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_corporate_actions_buybacks("HK.00700", num=3)
if ret == RET_OK:
    df = pd.DataFrame(data.get('hk_buy_back_list', []))
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
publ_date publ_date_str   end_date end_date_str  buy_back_money  buy_back_sum  percentage  high_price  low_price  cumulative_sum  cumulative_percentage      share_type
1775664000    2026-04-09 1775664000   2026-04-09    1000880717.6       1964000    0.021373       514.5      503.0       119812000                1.30386 Ordinary shares
1775577600    2026-04-08 1775577600   2026-04-08    1000761103.7       1979000    0.021537       510.0      501.0       117848000                1.28249 Ordinary shares
1775059200    2026-04-02 1775059200   2026-04-02     300715258.5        615000    0.006693       496.0      485.2       115869000                1.26095 Ordinary shares
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
* Supports HK stocks, A-share stocks and funds.
:::

---

﻿# Get Corporate Actions - Stock Splits

`get_corporate_actions_stock_splits(code, next_key=None, num=None)`

* **Description**

    Get stock split / reverse split history for a stock (HK stocks have extra fields), supports pagination

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. US.AAPL; supports HK, US, JP, SG, MY stocks and funds)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key returned from the previous request to continue; "-1" means no more data)
    num|int|Page size  (Number of records per page, default 10, range 1~50)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns stock split data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" means no more data; pass this value as next_key in the next request to continue)
        split_list|list|Stock split list  (See split_list field table for each item)

    * split_list fields (stock split entry):

        Field|Type|Description
        :-|:-|:-
        dir_deci_pub_date|int|Announcement date timestamp  (Unix timestamp (seconds), in the market's timezone)
        dir_deci_pub_date_str|str|Announcement date  (Format YYYY-MM-DD, in the market's timezone)
        reform_type|str|Reorganization type
        rate|str|Rate
        ex_date|int|Ex-rights date timestamp  (HK stocks only; Unix timestamp (seconds), in the market's timezone)
        ex_date_str|str|Ex-rights date  (HK stocks only; format YYYY-MM-DD, in the market's timezone)
        sm_deci_date|int|Resolution date timestamp  (HK stocks only; Unix timestamp (seconds), in the market's timezone)
        sm_deci_date_str|str|Resolution date  (HK stocks only; format YYYY-MM-DD, in the market's timezone)
        temp_trade_begin_date|int|Temporary trading date timestamp  (HK stocks only; Unix timestamp (seconds), in the market's timezone)
        temp_trade_begin_date_str|str|Temporary trading date  (HK stocks only; format YYYY-MM-DD, in the market's timezone)
        simul_trade_begin_date|int|Parallel trading start date timestamp  (HK stocks only; Unix timestamp (seconds), in the market's timezone)
        simul_trade_begin_date_str|str|Parallel trading start date  (HK stocks only; format YYYY-MM-DD, in the market's timezone)
        simul_trade_end_date|int|Parallel trading end date timestamp  (HK stocks only; Unix timestamp (seconds), in the market's timezone)
        simul_trade_end_date_str|str|Parallel trading end date  (HK stocks only; format YYYY-MM-DD, in the market's timezone)
        event_status|str|Event process  (HK stocks only; e.g. Scheme Implementation)
        new_par_value|float|New par value  (HK stocks only)
        temp_share_code|str|Temporary share code  (HK stocks only; e.g. 02988)
        temp_share_abbr_name|str|Temporary share abbreviation  (HK stocks only; e.g. Tencent Holdings)
        new_trade_unit|int|New board lot size  (HK stocks only; e.g. 100)
        shares_after_effect|float|Shares after effect  (HK stocks only; unit: shares)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_corporate_actions_stock_splits("HK.00700", num=3)
if ret == RET_OK:
    df = pd.DataFrame(data.get('split_list', []))
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
dir_deci_pub_date dir_deci_pub_date_str reform_type rate    ...  temp_share_abbr_name  new_trade_unit  shares_after_effect
        1395158400            2014-03-19       Split 1->5    ...               Tencent             100         9319999970.0
```

:::tip Interface Limit
* Maximum 30 requests per 30 seconds.
* Supports HK, US, JP, SG, MY stocks and funds.
:::

---

﻿# Get Shareholders Overview

`get_shareholders_overview(code, period_id=None)`

* **Description**

    Get shareholder overview for a stock, returning both major shareholders and holder type data

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports HK, US, SG, JP, MY stocks and funds)
    period_id|int|Reporting period ID  (Pass 0 or omit to get the latest data and also return the available period list; period IDs can be obtained from the holding_period list)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns shareholder overview data dictionary</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * The returned dictionary contains the following fields:

        Field|Type|Description
        :-|:-|:-
        main_holder|pd.DataFrame|Major shareholders list  (See main_holder field table for each item)
        holder_type|pd.DataFrame|Holder type list  (See holder_type field table for each item; same structure as main_holder, holder_id is always 0)
        holding_period|pd.DataFrame|Available reporting period list  (Only returned when period_id is 0 or not provided; see holding_period field table for each item)

    * main_holder / holder_type fields (shareholder statistic entry):

        Field|Type|Description
        :-|:-|:-
        static_date|int|Statistic date timestamp  (Unix timestamp (seconds), in the market's timezone)
        static_date_str|str|Statistic date  (Format YYYY-MM-DD, in the market's timezone)
        name|str|Holder name  (Holder or group name)
        holder_pct|float|Holding percentage  (Value before the percent sign, e.g. 23.05 means 23.05%)
        holder_id|int|Holder ID  (Has a value in main_holder; always 0 in holder_type)

    * holding_period fields (available reporting period entry):

        Field|Type|Description
        :-|:-|:-
        period_text|str|Reporting period  (e.g. "2025/Q3")
        period_id|int|Reporting period ID  (Pass this value as period_id in the next request)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_shareholders_overview("HK.00700")
if ret == RET_OK:
    df = data.get('main_holder')
    if df is not None:
        print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
static_date static_date_str                              name  holder_pct   holder_id
  1778469309      2026-05-11              Prosus Ventures N.V.    23.05351 337488017.0
  1778469309      2026-05-11                        Huateng Ma     7.86952  10253703.0
  1778469309      2026-05-11                      The Vanguard     2.97766    417222.0
  1778469309      2026-05-11                         BlackRock     2.66990    403413.0
  1778469309      2026-05-11 Norges Bank Investment Management     1.36075  27081864.0
  1778469309      2026-05-11                             Other    62.06866         NaN
```

:::tip Rate Limit
* Maximum 30 requests per 30 seconds.
* Supports HK, US, SG, JP, MY stocks and funds.
:::

---

﻿# Get Shareholders Holding Changes

`get_shareholders_holding_changes(code, next_key=None, num=None, sort_type=None, sort_column=None, filter_type=None)`

* **Description**

    Get shareholder holding change records for a stock, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports HK, US, SG, MY, JP stocks and funds)
    next_key|str|Pagination key  (Omit for the first request; pass the next_key returned from the previous response for subsequent pages; "-1" means no more data)
    num|int|Page size  (Default 10, range 1~50)
    sort_type|SortType|Sort direction  (1=Descending (default), 2=Ascending)
    sort_column|SortField|Sort field  (62=Share change num (default), 63=Holding date, 64=Holder pct change, 65=Holder change amount, 66=Holder pct)
    filter_type|HoldingChangesFilterType|Filter type  (0=All (default), 1=Increase, 2=Decrease, 3=New In, 4=Close Out)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns holding changes DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field descriptions:

        Field|Type|Description
        :-|:-|:-
        period_text|str|Reporting period  (e.g. "2026/Q1")
        name|str|Holder name
        holder_id|int|Holder ID  (Used to query historical holding change details)
        share_change_num|int|Share change number  (Unit: shares)
        shares_change_price|int|Reference change amount  (Unit: HKD or USD depending on market)
        share_ratio|float|Holding percentage  (Value before the percent sign, e.g. 12.34 means 12.34%)
        holder_type|str|Holder type  (Text description, e.g. "Traditional Investment Manager")
        holder_type_id|int|Holder type ID  (Used to query historical holding change details)
        holding_date_str|str|Holding date  (Format YYYY-MM-DD, Hong Kong timezone)
        share_ratio_change|float|Holding change ratio  (Value before the percent sign, e.g. 12.34 means a change of 12.34%)
        share_num|int|Shares held  (Unit: shares)
        next_key|str|Pagination key  ("-1" means no more data; pass as-is in the next request's next_key parameter)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_shareholders_holding_changes("HK.00700")
if ret == RET_OK:
    print(data[['period_text', 'name', 'share_change_num', 'share_ratio', 'share_ratio_change']].to_string(index=False))
    print('next_key:', data['next_key'][0])
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
period_text                                    name  share_change_num  share_ratio  share_ratio_change
    2026/Q1                               BlackRock           7971983        2.669               0.088
    2026/Q1           CSOP Asset Management Limited           6691695        0.192               0.074
    2026/Q1 Hang Seng Investment Management Limited           4870059        0.395               0.053
    2026/Q1                       GQG Partners, LLC           3289800        0.146               0.036
    2026/Q1                            The Vanguard           2837500        2.977               0.031
    2026/Q1     Pinebridge Investments Asia Limited           2316700        0.073               0.025
    2026/Q1                        Capital Research           2214900        0.948               0.024
    2026/Q1                        Australian Super           2214046        0.116               0.024
    2026/Q1 Mirae Asset Global Investments Co., Ltd           1852929        0.096               0.020
    2026/Q1                         Baillie Gifford           1831832        0.395               0.020
next_key: 10
```

:::tip API Limits
* Max 30 requests per 30 seconds.
* Supports HK, US, SG, MY, JP stocks and funds.
:::

---

﻿# Get Shareholders Holder Detail

`get_shareholders_holder_detail(code, request_type=None, next_key=None, num=None, sort_column=None, sort_type=None, period_id=None, holder_id=None)`

* **Description**

    Get the holder detail list for a stock under a specified holder type, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. US.AAPL; supports HK, US, SG, JP, MY stocks and funds)
    request_type|[HolderDetailType](./quote.md#9174)|Holder type  (0=Default, 1000=All, 1=Other Institution, 2=Traditional Investment Manager, 3=Hedge Fund, 4=Venture/Private Equity, 5=Corporate Pension, 6=Foundation Fund, 7=Insurance Company, 8=Bank/Investment Bank, 9=Family Office/Trust, 10=Sovereign Wealth Fund, 11=REIT, 12=Structured Finance Manager, 13=Union Pension, 14=Government Pension, 15=Endowment Fund, 100=Individual, 200=ADS, 300=Listed Company, 400=Unlisted Company, 500=State-Owned Shares; default returns per server-side logic)
    next_key|str|Pagination key  (Omit for the first request; pass the next_key returned from the previous response for subsequent pages; "-1" means no more data)
    num|int|Page size  (Default 10, range 1~50)
    sort_column|[SortField](./quote.md#5823)|Sort field  (61=Holder quantity (default), 62=Share change num)
    sort_type|[SortType](./quote.md#7778)|Sort direction  (1=Descending (default), 2=Ascending)
    period_id|int|Reporting period ID  (Matches the periodId in holdingPeriodList returned by GetShareholdersOverview (3237); default 0 means the latest period)
    holder_id|int|Holder ID filter  (Default 0 means no filter; can be obtained from the holder_id returned by GetShareholdersOverview (3237), GetShareholdersHoldingChanges (3238), this protocol (3239), GetInsiderHolderList (3241), or GetInsiderTradeList (3242))

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns holder detail DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field descriptions:

        Field|Type|Description
        :-|:-|:-
        update_time_str|str|Data update time  (Format YYYY-MM-DD HH:MM:SS, corresponding market timezone)
        next_key|str|Pagination key  ("-1" means no more data; pass as-is in the next request's next_key parameter)
        period_text|str|Reporting period  (e.g. "2026/Q1")
        holder_id|int|Holder ID  (Can be used as holder_id filter in other shareholder-related protocols)
        name|str|Holder name
        holder_quantity|int|Total shares held  (Unit: shares)
        holder_quantity_change|int|Share change number  (Unit: shares; positive means increased, negative means decreased)
        holder_pct|float|Holding percentage  (Value before the percent sign, e.g. 12.34 means 12.34%)
        holder_pct_change|float|Holding change ratio  (Value before the percent sign, e.g. 12.34 means a change of 12.34%; negative means decrease)
        holding_date_str|str|Holding date  (Format YYYY-MM-DD, Hong Kong timezone)
        close_price|float|Closing price on holding date  (Actual closing price corresponding to the holding date)
        price_change_pct|float|Price change percentage  (Value before the percent sign, e.g. -0.4467 means -0.4467%)
        source_group_name|str|Data source  (Disclosure source of holder detail, e.g. "13F", "13F Summary", etc.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_shareholders_holder_detail("HK.00700", request_type=1000)
if ret == RET_OK:
    print(data[['period_text', 'name', 'holder_quantity', 'holder_pct', 'holder_pct_change']].to_string(index=False))
    print('next_key:', data.attrs.get('next_key', '-1'))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
period_text                               name  holder_quantity  holder_pct  holder_pct_change
    2026/Q1               Prosus Ventures N.V.       2079512000      23.053             -0.285
    2026/Q1                         Huateng Ma        709859700       7.869              0.000
    2026/Q1                       The Vanguard        268596433       2.977              0.031
    2026/Q1                          BlackRock        240834898       2.669              0.088
    2026/Q1  Norges Bank Investment Management        122744699       1.360             -0.083
    2026/Q1                                FMR         86765121       0.961             -0.232
    2026/Q1                   Capital Research         85568118       0.948              0.024
    2026/Q1 J.P. Morgan Asset Management, Inc.         62437911       0.692             -0.025
    2026/Q1        E Fund Management Co., Ltd.         52722677       0.584              0.000
    2026/Q1                    Baillie Gifford         35674108       0.395              0.020
next_key: 10
```

:::tip Interface Limits
* Max 30 requests per 30 seconds.
* Supports HK, US, SG, JP, MY stocks and funds.
* Supports pagination; default page size is 10; pagination key is of string type.
:::

---

﻿# Get Institutional Holdings

`get_shareholders_institutional(code, next_key=None, num=None)`

* **Description**

    Get the institutional holding count and share quantity history for a stock, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. US.AAPL; supports HK, US, SG, JP, MY stocks and funds)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key returned from the previous response for subsequent pages; "-1" means no more data)
    num|int|Items per page  (Default 10, range 1~50)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns institutional holdings DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        period_text|str|Reporting period  (e.g. "2026/Q1")
        institution_quantity|int|Number of institutions  (Unit: institution count)
        institution_quantity_change|int|Institution count change  (Positive means increase, negative means decrease)
        holder_quantity|int|Total shares held  (Unit: shares)
        holder_quantity_change|int|Share count change  (Unit: shares; positive means added, negative means reduced)
        holder_pct|float|Holding percentage  (Value before the percent sign, e.g. 12.34 means 12.34%)
        holder_pct_change|float|Holding percentage change  (Value before the percent sign, e.g. 12.34 means a change of 12.34%; negative means decrease)
        update_time_str|str|Data update time  (Format YYYY-MM-DD HH:MM:SS, in the corresponding market timezone)
        next_key|str|Pagination key  ("-1" means no more data; pass as-is in next_key for subsequent requests)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_shareholders_institutional("HK.00700")
if ret == RET_OK:
    print(data[['period_text', 'institution_quantity', 'holder_quantity', 'holder_pct']].to_string(index=False))
    print('next_key:', data.attrs.get('next_key', '-1'))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
period_text  institution_quantity  holder_quantity  holder_pct
    2026/Q1                   863       4192178205      46.474
    2025/Q4                   873       4195284653      46.444
    2025/Q3                   854       4219387239      46.614
    2025/Q2                   839       4254708217      46.881
    2025/Q1                   809       4236696253      46.491
    2024/Q4                   808       4331865949      47.431
    2024/Q3                   803       4404605110      47.919
    2024/Q2                   846       4438538978      47.926
    2024/Q1                   824       4484844061      48.055
    2023/Q4                   857       4472729401      47.717
next_key: -1
```

:::tip API Limits
* Maximum 30 requests per 30 seconds.
* Supports HK, US, SG, JP, MY stocks and funds.
* Supports pagination; default 10 items per page; pagination key is a string type.
:::

---

﻿# Get Insider Holder List

`get_insider_holder_list(code, next_key=None, num=None)`

* **Description**

    Get the list of insider holders (executives/directors/major shareholders) for a US stock, with pagination support; the first page additionally returns an insider summary

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. US.AAPL; supports US and SG stocks and funds)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key returned from the previous response for subsequent pages; "-1" means no more data)
    num|int|Items per page  (Default 10, range 1~20)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns insider holder DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        holder_id|int|Holder ID  (Can be used as input for get_insider_trade_list and get_shareholders_holder_detail)
        holder_quantity|int|Total shares held  (Unit: shares)
        holder_pct|float|Holding ratio  (Value before the percent sign; e.g. 12.34 means 12.34%)
        name|str|Holder name
        title|str|Holder title
        all_count|int|Total count
        next_key|str|Pagination key  ("-1" means no more data; pass as-is for subsequent pages)
        insider_total_count|int|Total insider count  (Returned only on the first page (when next_key is empty))
        insider_bought_count|int|Bought count  (Number of insiders who bought; returned only on the first page)
        insider_sold_count|int|Sold count  (Number of insiders who sold; returned only on the first page)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_insider_holder_list("US.AAPL")
if ret == RET_OK:
    print(data[['holder_id', 'name', 'title', 'holder_quantity', 'holder_pct']].to_string(index=False))
    print('insider_total:', data['insider_total_count'].iloc[0])
    print('next_key:', data['next_key'].iloc[0])
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
holder_id             name                                 title  holder_quantity  holder_pct
    234085  Arthur Levinson Independent Non-Executive Chairperson          4125576       0.028
    169600     Timothy Cook               Chief Executive Officer          3280418       0.022
 626415138       Sabih Khan                               Officer          1105527       0.007
  34123508 Katherine  Adams                 Senior Vice President           175408       0.001
 531640091  Deirdre O’Brien       Senior Vice President of Retail           136810       0.000
    285767     Ronald Sugar                  Independent Director           110566       0.000
  50035778     Luca Maestri               Chief Financial Officer            91304       0.000
    253136      Andrea Jung                  Independent Director            77664       0.000
  22072913     Susan Wagner                  Independent Director            69788       0.000
1976351584      Ben Borders          Principal Accounting Officer            39987       0.000
insider_total: 17
next_key: 10
```

:::tip API Limitations
* Maximum 30 requests per 30 seconds.
* Only meaningful for US and SG stocks and funds.
* Supports pagination; default 10 items per page, maximum 20; the pagination key is a string type.
* The insider summary (total/bought/sold count) is only returned on the first page (when nextKey is empty).
:::

---

# Get Insider Trade List

`get_insider_trade_list(code, holder_id=None, num=None, next_key=None)`

* **Description**

    Get insider (executives/directors/major shareholders) trade records for a US stock, with optional holder filter and pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. US.AAPL; supports US and SG equities and funds)
    holder_id|int|Holder ID  (Omit to query all insiders; can be obtained from get_insider_holder_list (3241) or from this API's returned holder_id)
    num|int|Results per page  (Default 10, range 1~50)
    next_key|str|Pagination key  (Omit for first page; pass the value returned from the previous call for subsequent pages; "-1" means no more data)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns insider trade DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        trade_shares|int|Shares traded  (Positive for buy/acquire, negative for sell)
        min_trade_date|int|Minimum trade date timestamp  (Unix timestamp (seconds), market timezone)
        min_trade_date_str|str|Minimum trade date string  (Format YYYY-MM-DD, market timezone)
        max_trade_date|int|Maximum trade date timestamp  (Unix timestamp (seconds), market timezone)
        max_trade_date_str|str|Maximum trade date string  (Format YYYY-MM-DD, market timezone)
        min_price|float|Minimum trade price
        max_price|float|Maximum trade price
        security_holder_quantity|int|Securities held after trade  (Total shares held after the transaction; may be null for proposed sales)
        is_proposed_sale_of_securities|bool|Proposed sale  (Whether this is a proposed sale of securities (Form 144 filing))
        holder_id|int|Holder ID
        name|str|Holder name
        title|str|Holder title
        security_description|str|Security type description  (e.g. "Common Stock")
        transaction_type|str|Transaction type  (e.g. "Sell", "Exercise and acquire", "Exercise and sell", "Proposed sale", etc.)
        source_group_name|str|Data source  (e.g. "Form 4", "Form 144")
        all_count|int|Total record count
        next_key|str|Pagination key  ("-1" means no more data; pass as-is for the next page request)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_insider_trade_list("US.AAPL")
if ret == RET_OK:
    print(data[['holder_id', 'name', 'title', 'transaction_type', 'trade_shares']].to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
holder_id             name                                 title                       transaction_type  trade_shares
    234085  Arthur Levinson Independent Non-Executive Chairperson                Open Market Disposition       -250000
    234085  Arthur Levinson Independent Non-Executive Chairperson                      Other Disposition         -5000
  34123508 Katherine  Adams                 Senior Vice President              Intent to Sell (Form 144)        -43000
1892533533     Kevan Parekh               Chief Financial Officer                  Automatic Disposition         -1534
1892533533     Kevan Parekh               Chief Financial Officer Derivative Exercise and Retained Stock          6135
1892533533     Kevan Parekh               Chief Financial Officer           Derivative Exercise and Sale         -4793
1976351584      Ben Borders          Principal Accounting Officer Derivative Exercise and Retained Stock           825
1976351584      Ben Borders          Principal Accounting Officer           Derivative Exercise and Sale          -892
    169600     Timothy Cook               Chief Executive Officer              Intent to Sell (Form 144)        -64949
 531640091  Deirdre O’Brien       Senior Vice President of Retail              Intent to Sell (Form 144)        -30002
```

:::tip API Limits
* Max 30 requests per 30 seconds.
* Only meaningful for US and SG equities and funds.
* Supports pagination; default 10 results per page, max 50; pagination key is a string.
* holderId can be obtained from GetInsiderHolderList (3241) or from this protocol's (3242) return value.
:::

---

﻿# Get Company Profile

`get_company_profile(code)`

* **Description**

    Get the company profile tag list for the specified stock, including text fields, hyperlinks, and section titles

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports equities and funds)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns company profile DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        name|str|Tag name
        value|str|Tag content
        field_type|[CompanyProfileFieldType](./quote.md#1461)|Tag type  (0=SourceText (plain text), 1=LinkType (hyperlink), 2=IndependentTitle (section heading))

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_company_profile("HK.00700")
if ret == RET_OK:
    print(data.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
field_type  name                                 value
0           Symbol                               00700
0           Company Name                         TENCENT
0           ISIN                                 KYG875721634
0           Listing Date                         Jun 16, 2004
0           Issue Price                          3.70
0           Shares Offered                       420.16M share(s)
0           Founded                              Nov 23, 1999
0           Registered Address                   Cayman Islands
0           Chairman                             huateng ma
0           Audit Institution                    PwC
0           Company Category                     Overseas registratio ...
0           Registered Office                    Cricket Square, ...
0           Head Office and ...                  29th Floor, Tower 3,...
0           Fiscal Year Ends                     12-31
0           Employees                            115849
0           Market                               Hong Kong motherboard
0           Phone                                (852) 2179-5122
0           Fax                                  (852) 2520-1148
0           Email                                ir@tencent.com
1           Website                              http://www.tencent.com
2           Business                             Tencent Holdings Ltd is...
2           Description                          Tencent leverages ...
```

:::tip API Limits
* Max 30 requests per 30 seconds.
* Supports equities and funds.
:::

---

# Get Company Executives

`get_company_executives(code)`

* **Description**

    Get the list of directors and executives for the specified stock, including display name, name, position, start date, publish date, gender, age, education, and annual salary

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports equities and funds)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns executives DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        display_leader_name|str|Display name  (For display only; do not use as input to get_company_executive_background)
        leader_name|str|Executive name  (Can be passed to get_company_executive_background to query background)
        position_name|str|Position name
        begin_date|int|Start date timestamp (seconds)
        begin_date_str|str|Start date  (Format YYYY-MM-DD, in the market's timezone)
        leader_gender|str|Gender  (e.g. "Male" / "Female")
        leader_age|str|Age
        highest_education|str|Highest education level
        annual_salary|int|Annual salary
        issue_date|int|Publish date timestamp (seconds)
        issue_date_str|str|Publish date  (Format YYYY-MM-DD, in the market's timezone)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_company_executives("US.AAPL")
if ret == RET_OK:
    print(data[['display_leader_name', 'position_name', 'begin_date_str', 'annual_salary']].to_string(index=False))
    print('count:', len(data))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
display_leader_name                                                          position_name  begin_date_str  annual_salary
            Timothy D. Cook                                   Director and Chief Executive Officer             NaN     74294811.0
                 Sabih Khan                                                Chief Operating Officer             NaN     27031671.0
               Kevan Parekh                      Chief Financial Officer and Senior Vice President             NaN     22467309.0
                Ben Borders Principal Accounting Officer and Senior Director, Corporate Accounting             NaN            NaN
         Katherine L. Adams                                                  Senior Vice President             NaN     27032248.0
            Deirdre O'Brien                               Senior Vice President, Retail and People             NaN     27047633.0
       Jennifer G. Newstead                   Senior Vice President, General Counsel and Secretary             NaN            NaN
                John Ternus                            Senior Vice President, Hardware Engineering             NaN            NaN
Dr. Arthur D. Levinson, PhD                                                  Chairman of the Board             NaN       557231.0
            Susan L. Wagner                                                   Independent Director             NaN       445373.0
           Monica C. Lozano                                                   Independent Director             NaN       412956.0
                Andrea Jung                                                   Independent Director             NaN       458020.0
                Alex Gorsky                                                   Independent Director             NaN       416492.0
   Dr. Wanda M. Austin, PhD                                                   Independent Director             NaN       412850.0
        Dr. Ronald D. Sugar                                                   Independent Director             NaN       471283.0
count: 15
```

:::tip API Limits
* Max 30 requests per 30 seconds.
* Supports equities and funds.
:::

---

# Get Company Executive Background

`get_company_executive_background(code, leader_name=None)`

* **Description**

    Get the background profile of a specified executive for the given stock

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports equities and funds)
    leader_name|str|Executive name  (Use the leader_name field value returned by get_company_executives)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns executive background dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * dict field description:

        Field|Type|Description
        :-|:-|:-
        brief_background|str|Executive background profile

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_company_executive_background("US.AAPL", leader_name="Mr. Timothy D. Cook")
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
{'brief_background': "On April 20, 2026, Apple Inc. announced that Tim Cook will transition from his role as Chief Executive Officer to Executive Chair of Apple's Board of Directors, effective September 1, 2026. Mr. Cook, 65, has served as Apple's Chief Executive Officer since 2011, having previously served as Apple's Chief Operating Officer from October 2005. Mr. Cook joined Apple in March 1998 and served as Executive Vice President, Worldwide Sales and Operations from February 2002 to October 2005. From October 2000 to February 2002, Mr. Cook served as Senior Vice President, Worldwide Operations, Sales, Service and Support. From March 1998 to October 2000, Mr. Cook served as Senior Vice President, Worldwide Operations. Mr. Cook serves on the Board of Directors of The National Football Foundation & College Hall of Fame, Inc., the Board of Trustees of Duke University, and on the Leadership Council for the Malala Fund, an international non-profit organization that advocates for girls' education. Other Public Company Boards: Current: NIKE, Inc."}
```

:::tip API Limits
* Max 30 requests per 30 seconds.
* Supports equities and funds.
:::

---

﻿# Get Company Operational Efficiency

`get_company_operational_efficiency(code, num=None, next_key=None, currency_code=None)`

* **Description**

    Get company operational efficiency data for the specified stock, including employee count, revenue per capita, operating profit per capita, and net profit per capita.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (e.g. HK.00700; supports equities and funds)
    num|int|Number of records per page  (Default 10, range 1~50)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key from the previous response to fetch more; "-1" means no more data)
    currency_code|str|Currency code  (ISO 4217, e.g. CNY, USD, HKD, SGD, JPY, CAD, AUD; returns default currency if not specified)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../moomooapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns operational efficiency data dict</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return dict fields:

        Field|Type|Description
        :-|:-|:-
        item_list|list|Operational efficiency list; each item is a dict, fields shown below
        next_key|str|Pagination key  ("-1" means no more data)
        currency_code|str|Currency code  (ISO 4217)

    * item_list sub-item fields:

        Field|Type|Description
        :-|:-|:-
        fiscal_year|int|Fiscal year  (e.g. 2024)
        financial_type|[F10Type](./quote.md#7667)|Financial report type
        period_text|str|Report period  (e.g. "2024/Q3", "2024/FY")
        end_date|int|Period end timestamp  (Unix timestamp in seconds)
        end_date_str|str|Period end date string  (Format YYYY-MM-DD, in the market's timezone)
        employee_num|int|Number of employees
        employee_num_yoy|float|YoY change in employee count  (Value before %; e.g. 12.34 means 12.34%)
        income_per_capita|float|Revenue per capita
        income_per_capita_yoy|float|YoY change in revenue per capita  (Value before %; e.g. 12.34 means 12.34%)
        profit_per_capita|float|Operating profit per capita
        profit_per_capita_yoy|float|YoY change in operating profit per capita  (Value before %; e.g. 12.34 means 12.34%)
        net_profit_per_capita|float|Net profit per capita
        net_profit_per_capita_yoy|float|YoY change in net profit per capita  (Value before %; e.g. 12.34 means 12.34%)

* **Example**

```python
from moomoo import *
import pandas as pd
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_company_operational_efficiency("HK.00700")
if ret == RET_OK:
    df = pd.DataFrame(data.get('item_list', []))
    print(df.to_string(index=False))
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
fiscal_year period_text   end_date end_date_str  employee_num  employee_num_yoy  income_per_capita  income_per_capita_yoy  profit_per_capita  profit_per_capita_yoy  net_profit_per_capita  net_profit_per_capita_yoy
        2025     2025/FY 1767110400   2025-12-31        115849            4.7857       6489188.5126                 8.6594       2085145.3184                10.7787           1983625.2362                    11.6246
        2024     2024/FY 1735574400   2024-12-31        110558            4.8768       5972041.8242                 3.3726       1882260.8947                23.9566           1777049.1506                    58.6906
        2023     2023/FY 1703952000   2023-12-31        105417           -2.7841       5777199.1234                12.9662       1518483.7360                48.5723           1119819.3839                   -35.6529
        2022     2022/FY 1672416000   2022-12-31        108436           -3.8440       5114094.9500                 2.9643       1022049.8727               -57.5666           1740279.9808                   -13.8522
        2021     2021/FY 1640880000   2021-12-31        112771           31.3459       4966862.0478               -11.5377       2408597.9551                12.2453           2020111.5535                     8.3170
        2020     2020/FY 1609344000   2020-12-31         85858           36.5317       5614666.0765                -6.4170       2145833.8186                13.6879           1864998.0199                    22.3097
        2019     2019/FY 1577721600   2019-12-31         62885           15.7911       5999666.0570                 4.2027       1887477.1408                 4.9760           1524815.1387                     3.5346
        2018     2018/FY 1546185600   2018-12-31         54309           21.2362       5757682.8886                 8.4796       1798007.6966               -10.8064           1472757.7381                    -8.9654
        2017     2017/FY 1514649600   2017-12-31         44796           15.5280       5307616.7514                35.4518       2015849.6294                39.2885           1617800.6964                    51.3504
        2016     2016/FY 1483113600   2016-12-31         38775           26.5461       3918452.6112                16.7235       1447246.9374                 9.1517           1068910.3803                    12.5205
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* Supports equities and funds.
:::

---

# Get Top Ten Buy/Sell Brokers

`get_top_ten_buy_sell_brokers(code, days_before=None)`

* **Description**

    Get the top ten net buy and net sell broker lists for the specified HK stock (real-time or historical)

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code  (HK stocks only (equities and funds), e.g. HK.00700)
    days_before|int|Historical days  (Leave empty or 0 = real-time data (includes avg price / total volume / total turnover); >0 = historical data for the N-th previous trading day (net volume and broker name only))

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../moomooapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns broker data DataFrame</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        is_real_time|bool|Whether real-time data  (true = real-time, false = historical)
        data_time|int|Data update timestamp  (Unix timestamp in seconds)
        data_time_str|str|Data update time string  (Format YYYY-MM-DD HH:MM:SS, in the market's timezone)
        net_vol|int|Net buy/sell volume  (Positive for net buy, negative for net sell)
        broker_name|str|Broker display name  (Real-time uses broker profile data; historical uses the name from the response)
        buy_sell_type|[BuySellType](./quote.md#5020)|Buy/sell type
        avg_price|float|Average trade price  (Real-time data only)
        total_vol|float|Total trade volume  (Real-time data only)
        total_turnover|float|Total trade turnover  (Real-time data only)

* **BuySellType Enum**

    Enum Name|Value|Description
    :-|:-|:-
    Unknown|0|Unknown
    NetBuy|1|Net buy
    NetSell|2|Net sell

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_top_ten_buy_sell_brokers("HK.00700")
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close()
```

* **Output**

```python
net_vol  is_real_time  buy_sell_type  ...   avg_price total_vol total_turnover
0     99200          True              1  ...  466.852156  398800.0    186180640.0
1     46500          True              1  ...  466.508972   61300.0     28597000.0
2     45400          True              1  ...  466.224332   67400.0     31423520.0
3     36000          True              1  ...  467.343428  240400.0    112349360.0
4     31300          True              1  ...  466.900580  155100.0     72416280.0
5     30000          True              1  ...  465.546667   30000.0     13966400.0
6     15000          True              1  ...  466.809333   15000.0      7002140.0
7     13700          True              1  ...  466.816577   55500.0     25908320.0
8     12300          True              1  ...  466.557724   12300.0      5738660.0
9      9200          True              1  ...  466.217391    9200.0      4289200.0
10  -373700          True              2  ...  467.064060  414300.0    193504640.0
11  -235100          True              2  ...  466.822072  502900.0    234764820.0
12  -168100          True              2  ...  466.281052  311900.0    145433060.0
13  -138300          True              2  ...  467.436639  547500.0    255921560.0
14   -89800          True              2  ...  466.722515  265600.0    123961500.0
15   -79400          True              2  ...  466.431910   79600.0     37127980.0
16   -69700          True              2  ...  466.950688   94500.0     44126840.0
17   -43600          True              2  ...  466.546230   61000.0     28459320.0
18   -25300          True              2  ...  466.652174   25300.0     11806300.0
19   -19500          True              2  ...  466.124484   33900.0     15801620.0

[20 rows x 9 columns]
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* HK stocks only (equities and funds).
* `days_before=0` or omitted returns real-time data (includes avg price / total volume / total turnover); `days_before>0` returns net volume and broker name only.
:::

---

# Get Daily Short Volume

`get_daily_short_volume(stock_code, next_key=None, num=None)`

* **Description**

    Get daily short volume data for US or HK stocks, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    stock_code|str|Stock code  (Supports HK and US stocks and funds, e.g. US.AAPL, HK.00700)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key from the previous response to continue; "-1" indicates no more data)
    num|int|Page size  (Default 10, range 1~50)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../moomooapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td>us_df</td>
            <td>pd.DataFrame</td>
            <td>US daily short volume data; error description string when ret != RET_OK</td>
        </tr>
        <tr>
            <td>hk_df</td>
            <td>pd.DataFrame</td>
            <td>HK daily short volume data; None when ret != RET_OK</td>
        </tr>
    </table>

    * US DataFrame (us_df) field description:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Trading day timestamp  (Unix timestamp in seconds, midnight of the day)
        timestamp_str|str|Trading day string  (Format YYYY-MM-DD, in market timezone)
        total_shares_short|int|Total short shares
        nasdaq_shares_short|int|NASDAQ short shares
        nyse_shares_short|int|NYSE short shares
        short_percent|float|Short ratio  (Value before the percent sign, e.g. 12.34 means 12.34%)
        volume|int|Volume (shares)
        close_price|float|Close price
        last_close_price|float|Previous close price
        daily_trade_avg_ratio|float|Daily avg trade ratio  (Value before the percent sign, e.g. 12.34 means 12.34%; 20-trading-day average ending at the given trading day)

    * US us_df.attrs additional attributes:

        Attribute|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" indicates no more data)

    * HK DataFrame (hk_df) field description:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Trading day timestamp  (Unix timestamp in seconds, midnight of the day)
        timestamp_str|str|Trading day string  (Format YYYY-MM-DD, in market timezone)
        shares_traded|int|Volume (shares)
        turnover|float|Turnover
        short_sell_shares_traded|int|Short sell volume (shares)
        short_sell_turnover|float|Short sell turnover
        open_price|float|Open price
        close_price|float|Close price
        last_close_price|float|Previous close price
        daily_trade_avg_ratio|float|Daily avg trade ratio  (Value before the percent sign, e.g. 12.34 means 12.34%; 20-trading-day average ending at the given trading day)

    * HK hk_df.attrs additional attributes:

        Attribute|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" indicates no more data)
        aggregated_short|int|Aggregated short position (shares)  (HK only)
        aggregated_short_ratio|float|Ratio of outstanding shares  (Value before the percent sign, e.g. 12.34 means 12.34%; HK only)
        new_time_str|str|Latest data time  (Format YYYY-MM-DD, in market timezone; HK only)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, us_df, hk_df = quote_ctx.get_daily_short_volume("HK.00700")
if ret == RET_OK:
    print(hk_df)
else:
    print('error:', hk_df)
quote_ctx.close()
```

* **Output**

```python
timestamp timestamp_str  ...  last_close_price  daily_trade_avg_ratio
0  1778169600    2026-05-08  ...             477.4                  11.36
1  1778083200    2026-05-07  ...             463.0                  11.80
2  1777996800    2026-05-06  ...             472.2                  12.22
3  1777910400    2026-05-05  ...             473.0                  12.76
4  1777824000    2026-05-04  ...             467.8                  13.02
5  1777478400    2026-04-30  ...             479.2                  13.09
6  1777392000    2026-04-29  ...             473.8                  14.02
7  1777305600    2026-04-28  ...             478.6                  14.13
8  1777219200    2026-04-27  ...             493.4                  14.14
9  1776960000    2026-04-24  ...             495.2                  14.18

[10 rows x 10 columns]
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* Supports HK and US stocks and funds.
:::

---

# Get Short Interest

`get_short_interest(stock_code, next_key=None, num=None)`

* **Description**

    Get the short interest history for a specified HK or US stock, with pagination support

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    stock_code|str|Stock code  (Supports HK and US equities and funds, e.g. US.AAPL, HK.00700)
    next_key|str|Pagination key  (Leave empty for the first request; pass the next_key from the previous response to continue; "-1" means no more data)
    num|int|Page size  (Default 10, range 1~50)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td>us_df</td>
            <td>pd.DataFrame</td>
            <td>US short interest data; error string when ret != RET_OK</td>
        </tr>
        <tr>
            <td>hk_df</td>
            <td>pd.DataFrame</td>
            <td>HK short interest data; None when ret != RET_OK</td>
        </tr>
    </table>

    * US DataFrame (us_df) fields:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Trading day timestamp  (Unix timestamp in seconds, midnight of the trading day)
        timestamp_str|str|Trading day string  (Format YYYY-MM-DD, in the market's timezone)
        shares_short|int|Shares sold short
        short_percent|float|Short ratio  (Value before the percent sign, e.g. 12.34 means 12.34%)
        avg_daily_share_volume|int|Average daily share volume
        days_to_cover|float|Days to cover
        close_price|float|Close price
        last_close_price|float|Previous close price

    * US us_df.attrs additional attributes:

        Attribute|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" means no more data)

    * HK DataFrame (hk_df) fields:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Trading day timestamp  (Unix timestamp in seconds, midnight of the trading day)
        timestamp_str|str|Trading day string  (Format YYYY-MM-DD, in the market's timezone)
        close_price|float|Close price
        last_close_price|float|Previous close price
        aggregated_short|int|Aggregated short positions (shares)
        aggregated_short_ratio|float|Short ratio of shares outstanding  (Value before the percent sign, e.g. 12.34 means 12.34%)

    * HK hk_df.attrs additional attributes:

        Attribute|Type|Description
        :-|:-|:-
        next_key|str|Pagination key  ("-1" means no more data)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, us_df, hk_df = quote_ctx.get_short_interest("HK.00700")
if ret == RET_OK:
    print(hk_df)
else:
    print('error:', hk_df)
quote_ctx.close()
```

* **Output**

```python
   timestamp timestamp_str  aggregated_short  aggregated_short_ratio  close_price  last_close_price
0  1777478400    2026-04-30          51480638                    0.56        467.8             479.2
1  1776960000    2026-04-24          51888755                    0.56        493.4             495.2
2  1776355200    2026-04-17          47974208                    0.52        510.5             517.0
3  1775750400    2026-04-10          48424833                    0.53        504.5             508.5
4  1775059200    2026-04-02          49982828                    0.54        489.2             496.6
5  1774540800    2026-03-27          52744147                    0.57        493.4             495.6
6  1773936000    2026-03-20          51710854                    0.56        508.0             513.0
7  1773331200    2026-03-13          48105325                    0.52        547.5             546.5
8  1772726400    2026-03-06          42404275                    0.46        519.0             502.0
9  1772121600    2026-02-27          36037870                    0.39        518.0             512.0
```

:::tip Restrictions
* Maximum 30 requests per 30 seconds.
* Supports HK and US equities and funds.
:::

---

# Get Option Expiration Date

`get_option_expiration_date(code, index_option_type=IndexOptionType.NORMAL)`

* **Description**

    Query all expiration dates of option chains through the underlying stock. To obtain the complete option chain, please use it in combination with [Get Option Chain](../quote/get-option-chain.md).  

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    index_option_type|[IndexOptionType](../quote/quote.md#2866)|Index option type.  (Only valid for HK index options. Ignore this parameter for stocks, ETFs, and US index options.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, option expiration date data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Option expiration date data format as follows:
        Field|Type|Description
        :-|:-|:-
        strike_time|str|Exercise date.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        option_expiry_date_distance|int|The number of days from the expiry date.  (A negative number means it has expired.)
        expiration_cycle|[ExpirationCycle](./quote.md#5181)|Expiration cycle.  (For HK index options only)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_option_expiration_date(code='HK.00700')
if ret == RET_OK:
    print(data)
    print(data['strike_time'].values.tolist())  # Convert to list
else:
    print('error:', data)
quote_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
  strike_time  option_expiry_date_distance expiration_cycle
0  2021-04-29                            4              N/A
1  2021-05-28                           33              N/A
2  2021-06-29                           65              N/A
3  2021-07-29                           95              N/A
4  2021-09-29                          157              N/A
5  2021-12-30                          249              N/A
6  2022-03-30                          339              N/A
['2021-04-29', '2021-05-28', '2021-06-29', '2021-07-29', '2021-09-29', '2021-12-30', '2022-03-30']
```

:::tip Interface Limitations
* A maximum of 60 requests per 30 seconds
:::

---

# Get Option Chain

`get_option_chain(code, index_option_type=IndexOptionType.NORMAL, start=None, end=None, option_type=OptionType.ALL, option_cond_type=OptionCondType.ALL, data_filter=None)`

* **Description**

    Query the option chain from an underlying stock. This interface only returns the static information of the option chain. If you need to obtain dynamic information such as quotation or trading, please use the security code returned by this interface to [subscribe](../quote/sub.md) the required security.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Code of underlying stock.
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type.  (Only valid for HK index options. Ignore this parameter for stocks, ETFs, and US index options.)
    start|str|Start date, for expiration date.  (For example: "2017-08-01".)
    end|str|End date (including this day), for expiration date.  (For example: "2017-08-30".)
    option_type|[OptionType](./quote.md#9598)|Option type for call/put.  (Default all.)
    option_cond_type|[OptionCondType](./quote.md#9027)|Option type for in/out of the money.  (Default all.)
    data_filter|*OptionDataFilter*|Data filter condition.  (No filter by default.)
    * The combination of ***start*** and ***end*** is as follows:
        Start type|End type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 30 days before ***end***.
        str|None|***end*** is 30 days after ***start***.
        None|None|***start*** is the current date, ***end*** is 30 days later.

    * *OptionDataFilter* fields are as follows
        Field|Type|Description
        :-|:-|:-
        implied_volatility_min|float|Min value of implied volatility.  (0 decimal place accuracy, the excess part is discarded.)
        implied_volatility_max|float|Max value of implied volatility.  (0 decimal place accuracy, the excess part is discarded.)
        delta_min|float|Min value of Greek value Delta.  (3 decimal place accuracy, the excess part is discarded.)
        delta_max|float|Max value of Greek value Delta.  (3 decimal place accuracy, the excess part is discarded.)
        gamma_min|float|Min value of Greek value Gamma.  (3 decimal place accuracy, the excess part is discarded.)
        gamma_max|float|Max value of Greek value Gamma.  (3 decimal place accuracy, the excess part is discarded.)
        vega_min|float|Min value of Greek value Vega.  (3 decimal place accuracy, the excess part is discarded.)
        vega_max|float|Max value of Greek value Vega.  (3 decimal place accuracy, the excess part is discarded.)
        theta_min|float|Min value of Greek value Theta.  (3 decimal place accuracy, the excess part is discarded.)
        theta_max|float|Max value of Greek value Theta.  (3 decimal place accuracy, the excess part is discarded.)
        rho_min|float|Min value of Greek value Rho.  (3 decimal place accuracy, the excess part is discarded.)
        rho_max|float|Max value of Greek value Rho.  (3 decimal place accuracy, the excess part is discarded.)
        net_open_interest_min|float|Min value of net open contract number.  (0 decimal place accuracy, the excess part is discarded.)
        net_open_interest_max|float|Max value of net open contract number.  (0 decimal place accuracy, the excess part is discarded.)
        open_interest_min|float|Min value of open contract number.  (0 decimal place accuracy, the excess part is discarded.)
        open_interest_max|float|Max value of open contract number.  (0 decimal place accuracy, the excess part is discarded.)
        vol_min|float|Min value of Volume.  (0 decimal place accuracy, the excess part is discarded.)
        vol_max|float|Max value of Volume.  (0 decimal place accuracy, the excess part is discarded.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, option chain data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Option chain data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Security code.
        name|str|Security name.
        lot_size|int|Number of shares per lot, number of shares per contract for options.  (Index options do not have this field.)
        stock_type|[SecurityType](./quote.md#9767)|Stock type.
        option_type|[OptionType](./quote.md#9598)|Option type.
        stock_owner|str|Underlying stock.
        strike_time|str|Exercise date.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        strike_price|float|Strike price.
        suspension|bool|Whether is suspended.  (True: suspended. False: not suspended)
        stock_id|int|Stock ID.
        index_option_type|[IndexOptionType](./quote.md#2866)|Index option type.
        expiration_cycle|[ExpirationCycle](./quote.md#5181)|Expiration cycle type.
        option_standard_type|[OptionStandardType](./quote.md#8553)|Option standard type.
        option_settlement_mode|[OptionSettlementMode](./quote.md#6656)|Option settlement mode.

* **Example**

```python
from moomoo import *
import time
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret1, data1 = quote_ctx.get_option_expiration_date(code='HK.00700')

filter1 = OptionDataFilter()
filter1.delta_min = 0
filter1.delta_max = 0.1

if ret1 == RET_OK:
    expiration_date_list = data1['strike_time'].values.tolist()
    for date in expiration_date_list:
        ret2, data2 = quote_ctx.get_option_chain(code='HK.00700', start=date, end=date, data_filter=filter1)
        if ret2 == RET_OK:
            print(data2)
            print(data2['code'][0])  # Take the first stock code
            print(data2['code'].values.tolist())  # Convert to list
        else:
            print('error:', data2)
        time.sleep(3)
else:
    print('error:', data1)
quote_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
                     code                 name  lot_size stock_type option_type stock_owner strike_time  strike_price  suspension  stock_id index_option_type expiration_cycle option_standard_type
0     HK.TCH210429C350000   腾讯 210429 350.00 购       100       DRVT        CALL    HK.00700  2021-04-29         350.0       False  80235167               N/A        WEEK        STANDARD        
1     HK.TCH210429P350000   腾讯 210429 350.00 沽       100       DRVT         PUT    HK.00700  2021-04-29         350.0       False  80235247               N/A        WEEK        STANDARD
2     HK.TCH210429C360000   腾讯 210429 360.00 购       100       DRVT        CALL    HK.00700  2021-04-29         360.0       False  80235163               N/A        WEEK        STANDARD
3     HK.TCH210429P360000   腾讯 210429 360.00 沽       100       DRVT         PUT    HK.00700  2021-04-29         360.0       False  80235246               N/A        WEEK        STANDARD
4     HK.TCH210429C370000   腾讯 210429 370.00 购       100       DRVT        CALL    HK.00700  2021-04-29         370.0       False  80235165               N/A        WEEK        STANDARD
5     HK.TCH210429P370000   腾讯 210429 370.00 沽       100       DRVT         PUT    HK.00700  2021-04-29         370.0       False  80235248               N/A        WEEK        STANDARD
HK.TCH210429C350000
['HK.TCH210429C350000', 'HK.TCH210429P350000', 'HK.TCH210429C360000', 'HK.TCH210429P360000', 'HK.TCH210429C370000', 'HK.TCH210429P370000']
...
                   code                name  lot_size stock_type option_type stock_owner strike_time  strike_price  suspension  stock_id index_option_type expiration_cycle option_standard_type
0   HK.TCH220330C490000  腾讯 220330 490.00 购       100       DRVT        CALL    HK.00700  2022-03-30         490.0       False  80235143               N/A        WEEK        STANDARD    
1   HK.TCH220330P490000  腾讯 220330 490.00 沽       100       DRVT         PUT    HK.00700  2022-03-30         490.0       False  80235193               N/A        WEEK        STANDARD    
2   HK.TCH220330C500000  腾讯 220330 500.00 购       100       DRVT        CALL    HK.00700  2022-03-30         500.0       False  80233887               N/A        WEEK        STANDARD    
3   HK.TCH220330P500000  腾讯 220330 500.00 沽       100       DRVT         PUT    HK.00700  2022-03-30         500.0       False  80233912               N/A        WEEK        STANDARD    
4   HK.TCH220330C510000  腾讯 220330 510.00 购       100       DRVT        CALL    HK.00700  2022-03-30         510.0       False  80233747               N/A        WEEK        STANDARD    
5   HK.TCH220330P510000  腾讯 220330 510.00 沽       100       DRVT         PUT    HK.00700  2022-03-30         510.0       False  80233766               N/A        WEEK        STANDARD    
HK.TCH220330C490000
['HK.TCH220330C490000', 'HK.TCH220330P490000', 'HK.TCH220330C500000', 'HK.TCH220330P500000', 'HK.TCH220330C510000', 'HK.TCH220330P510000']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* The upper limit of the incoming time span is 30 days
:::

:::tip Tips
* This interface does not support the query of expired option chains, please enter today or future date to the **End date** parameter.
* Open interest (OI) is updated daily and the specific timing depends on the exchange.
    - For U.S. stock options, the data is updated during the PRE_MARKET session.
    - For Hong Kong stock options, the data is updated after the Regular Trading Hours.
:::

---

# Get Option Volatility

`get_option_volatility(code, query_time_period=None, hv_time_period=None)`

* **Description**

    Get implied volatility, historical volatility and volatility premium analysis for a specified option contract

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Option code  (Only option contract codes are supported, e.g. US.AAPL260427C270000)
    query_time_period|[OptionVolatilityTimePeriodType](./quote.md#2958)|Query time period  (Default is Month if not specified)
    hv_time_period|int|Historical volatility calculation period (days)  (Range 5~250, default 30)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>Option volatility data when ret == RET_OK</td>
        </tr>
        <tr>
            <td>str</td>
            <td>Error description string when ret != RET_OK</td>
        </tr>
    </table>

    * DataFrame field description:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Trading day timestamp  (Unix timestamp in seconds, midnight of the day)
        timestamp_str|str|Trading day string  (Format YYYY-MM-DD, in market timezone)
        implied_volatility|float|Implied volatility  (Value before % sign, e.g. 25.0 means 25%)
        history_volatility|float|Historical volatility  (Underlying historical volatility, value before % sign, e.g. 25.0 means 25%)
        volatility_premium|float|Volatility premium  (Implied minus historical volatility; positive value means implied is higher than historical)
        average_impvol|float|Average implied volatility  (Mean of implied volatility over the query period, value before % sign)
        impvol_status|[OptionImpvolStatusType](./quote.md#1046)|Volatility status
        analysis|str|Analysis text

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, df = quote_ctx.get_option_volatility("US.AAPL281215C320000", query_time_period=2, hv_time_period=30)
if ret == RET_OK:
    cols = ['timestamp_str', 'implied_volatility', 'history_volatility', 'volatility_premium']
    print(df[cols].to_string(index=False))
else:
    print('error:', df)
quote_ctx.close()
```

* **Output**

```
timestamp_str  implied_volatility  history_volatility  volatility_premium
   2026-04-13              27.813              18.977               8.836
   2026-04-14              27.656              18.962               8.694
   2026-04-15              27.726              20.782               6.944
   2026-04-16              28.069              21.013               7.056
   2026-04-17              27.796              22.088               5.708
   2026-04-20              28.054              21.931               6.123
   2026-04-21              27.897              23.194               4.703
   2026-04-22              28.276              24.300               3.976
   2026-04-23              27.951              24.296               3.655
   2026-04-24              28.056              23.676               4.380
   2026-04-27              27.917              22.985               4.932
   2026-04-28              27.942              23.011               4.931
   2026-04-29              28.269              23.022               5.247
   2026-04-30              27.630              22.312               5.318
   2026-05-01              27.576              23.741               3.835
   2026-05-04              27.919              24.078               3.841
   2026-05-05              27.308              24.778               2.530
   2026-05-06              27.746              24.850               2.896
   2026-05-07              28.198              24.886               3.312
   2026-05-08              27.719              25.285               2.434
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
* Only option contract codes are supported; underlying stock codes are not.
:::

---

# Get Option Exercise Probability

`get_option_exercise_probability(code)`

* **Description**

    Get historical exercise probability data for a specified option contract, sorted by date in descending order

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Option code  (Only option contract codes are supported, e.g. US.AAPL260427C270000)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns exercise probability data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        timestamp|int|Timestamp  (Unix timestamp in seconds)
        timestamp_str|str|Date string  (Format YYYY-MM-DD, in market timezone)
        security_price|float|Underlying price
        strike_probability|float|Exercise probability  (Value before the percent sign, e.g. 12.34 means 12.34%)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, df = quote_ctx.get_option_exercise_probability("US.AAPL281215C320000")
if ret == RET_OK:
    print(df)
else:
    print('error:', df)
quote_ctx.close()
```

* **Output**

```python
timestamp timestamp_str  security_price  strike_probability
0   1778469319    2026-05-10          293.32              41.869
1   1778212800    2026-05-08          293.05              41.887
2   1778126400    2026-05-07          287.17              40.011
3   1778040000    2026-05-06          287.24              40.122
4   1777953600    2026-05-05          283.91              38.956
5   1777867200    2026-05-04          276.56              36.861
6   1777608000    2026-05-01          279.87              37.939
7   1777521600    2026-04-30          271.08              35.189
8   1777435200    2026-04-29          269.90              34.851
9   1777348800    2026-04-28          270.44              35.040
10  1777262400    2026-04-27          267.34              34.094
11  1777003200    2026-04-24          270.79              35.170
12  1776916800    2026-04-23          273.16              35.885
13  1776830400    2026-04-22          272.90              35.805
14  1776744000    2026-04-21          265.90              33.691
15  1776657600    2026-04-20          272.78              35.799
16  1776398400    2026-04-17          269.96              34.964
17  1776312000    2026-04-16          263.13              32.901
18  1776225600    2026-04-15          266.16              33.834
19  1776139200    2026-04-14          258.56              31.536
20  1776052800    2026-04-13          258.93              31.663
21  1775793600    2026-04-10          260.21              32.069
22  1775707200    2026-04-09          260.22              32.086
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
* Only option contract codes are supported; underlying stock codes are not supported.
:::

---

# Get Option Strategy

`get_option_strategy(code, option_strategy, expire_time, spread=None, far_expire_time=None, index_option_type=IndexOptionType.NORMAL, option_type=OptionType.ALL, strike_price=None)`

* **Description**

    Query option chain legs by strategy type. Supports vertical spread, straddle, collar, butterfly, and other standard strategies.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Underlying stock code  (如 US.AAPL、HK.00700)
    option_strategy|[OptionStrategyType](./quote.md#9368)|Option strategy type
    expire_time|str|Expiration date  (Format: yyyy-MM-dd, in market timezone; required for Calendar spread and Diagonal spread)
    spread|float|Spread  (Required for Vertical spread, Strangle, Collar, Butterfly, Condor, Iron butterfly, Iron condor, and Diagonal spread)
    far_expire_time|str|Far expiration date  (Format: yyyy-MM-dd; required for Calendar spread and Diagonal spread)
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type  (Only effective for HK index option filtering)
    option_type|[OptionType](./quote.md#9598)|Option call/put type  (Default: all)
    strike_price|float|Strike price

    * Required parameters by strategy type:

        * **expire_time** Required for:`CALENDAR_SPREAD`（Calendar spread）、`DIAGONAL_SPREAD`（Diagonal spread）
        * **spread** Required for:`SPREAD`（Vertical spread）、`STRANGLE`（Strangle）、`COLLAR`（Collar）、`BUTTERFLY`（Butterfly）、`CONDOR`（Condor）、`IRON_BUTTERFLY`（Iron butterfly）、`IRON_CONDOR`（Iron condor）、`DIAGONAL_SPREAD`（Diagonal spread）
        * **far_expire_time** Required for:`CALENDAR_SPREAD`（Calendar spread）、`DIAGONAL_SPREAD`（Diagonal spread）

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns strategy list data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Strategy identifier code
        name|str|Strategy name
        option_strategy|str|Option strategy type  (如 STRADDLE)
        stock_owner|str|Underlying stock
        legs|list|Combo leg list  (Elements are OptionStrategyLeg)

    * OptionStrategyLeg fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Option contract code
        action|str|Buy/sell direction  (BUY / SELL)
        quantity|float|Quantity

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret,data = quote_ctx.get_option_strategy(code='HK.00700', option_strategy=OptionStrategyType.STRADDLE)
if ret == RET_OK:
    print(data)
    print(data['legs'][0])
else:
    print('error:', data)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
               code     name option_strategy stock_owner                                               legs
0   TCH260522C/P330  Tencent Straddle        STRADDLE    HK.00700  [OptionStrategyLeg(code=HK.TCH260522P330000, action=BUY, quantity=1.0), OptionStrategyLeg(code=HK.TCH260522C330000, action=BUY, quantity=1.0)]
1   TCH260522C/P340  Tencent Straddle        STRADDLE    HK.00700  [OptionStrategyLeg(code=HK.TCH260522P340000, a...
2   TCH260522C/P350  Tencent Straddle        STRADDLE    HK.00700  [OptionStrategyLeg(code=HK.TCH260522P350000, a...
...
26  TCH260522C/P590  Tencent Straddle        STRADDLE    HK.00700  [OptionStrategyLeg(code=HK.TCH260522P590000, a...
[OptionStrategyLeg(code=HK.TCH260522P330000, action=BUY, quantity=1.0), OptionStrategyLeg(code=HK.TCH260522C330000, action=BUY, quantity=1.0)]
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
:::

---

# Get Valid Spread

`get_option_strategy_spread(code, option_strategy, expire_time, far_expire_time=None, index_option_type=IndexOptionType.NORMAL)`

* **Description**

    Get the list of valid spreads for the specified option strategy under the current underlying and expiration date.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Underlying stock code  (如 US.AAPL、HK.00700)
    option_strategy|[OptionStrategyType](./quote.md#9368)|Option strategy type
    expire_time|str|Expiration date  (Format: yyyy-MM-dd, in market timezone)
    far_expire_time|str|Far expiration date  (Required for DiagonalSpread and similar strategies; format: yyyy-MM-dd)
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type  (Only effective for HK index option filtering)

    * option_strategy only supports Spread, Strangle, Collar, Butterfly, Condor, IronButterfly, IronCondor, and DiagonalSpread.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns valid spread list</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        spread|float|Valid spread

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret,data = quote_ctx.get_option_strategy_spread(code='HK.00700', option_strategy=OptionStrategyType.STRANGLE)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
    spread
0     10.0
1     20.0
2     30.0
3     40.0
4     50.0
5     60.0
6     70.0
7     80.0
8     90.0
9    100.0
10   110.0
11   120.0
12   130.0
13   140.0
14   150.0
15   160.0
16   170.0
17   180.0
18   190.0
19   200.0
20   210.0
21   220.0
22   230.0
23   240.0
24   250.0
25   260.0
```

:::tip API Restrictions
* Maximum 30 requests per 30 seconds.
:::

---

# Option Strategy Analysis

`get_option_strategy_analysis(combo_leg_list)`

* **Description**

    Perform P/L analysis on custom or multi-leg option combos and return P/L curves and related analytics.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    combo_leg_list|list|Combo leg list  (Elements are OptionStrategyLeg; structure see [get_option_strategy](./get-option-strategy.md))

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns option strategy analysis result</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Strategy identifier code
        name|str|Strategy name
        option_strategy|str|Option strategy type
        bid1|float|Combo bid price
        ask1|float|Combo ask price
        max_profit|float|Max profit
        max_loss|float|Max loss
        breakeven_points|list|Breakeven points
        prob_of_profit|float|Probability of profit  (This field is in percentage form, so 20 is equivalent to 20%.)
        delta|float|Delta
        theta|float|Theta

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_option_strategy(code='HK.00700', option_strategy=OptionStrategyType.STRADDLE)
if ret == RET_OK:
    index=0
    print(data['legs'][index])
    ret2,data2 = quote_ctx.get_option_strategy_analysis(data['legs'][index])
    if ret2 == RET_OK:
        print(data2)
    else:
        print("get_analysis,error:",data2)
else:
    print('error:', data)

quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
[OptionStrategyLeg(code=HK.TCH260522P330000, action=BUY, quantity=1.0), OptionStrategyLeg(code=HK.TCH260522C330000, action=BUY, quantity=1.0)]
              code     name option_strategy  bid1    ask1    max_profit  max_loss  breakeven_points  prob_of_profit     delta     theta
0  TCH260522C/P330  Tencent Straddle        STRADDLE   0.0  130.44  1.000000e+15  -13044.0  [199.56, 460.44]        0.315492  0.974369 -0.785757
```

:::tip API Restrictions
* Does not consume option subscription quota.
* Maximum 30 requests per 30 seconds.
:::

---

# Get Option Quote

`get_option_quote(combo_leg_list)`

* **Description**

    Get option snapshot quotes from a combo leg list, suitable for multi-leg strategy batch quote queries.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    combo_leg_list|list|Combo leg list  (Elements are OptionStrategyLeg; structure see [get_option_strategy](./get-option-strategy.md))

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns option snapshot data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        price|float|Combo price
        change_val|float|Change value
        change_rate|float|Change rate
        volume|str|Volume
        turnover|str|Turnover
        high_price|str|High price
        low_price|str|Low price
        mid_price|str|Mid price
        open_price|str|Open price
        last_close_price|float|Last close price
        open_interest|str|Open interest
        premium|str|Premium
        implied_volatility|str|Implied volatility
        delta|float|Delta
        gamma|float|Gamma
        vega|float|Vega
        theta|float|Theta
        rho|float|Rho
        option_type|str|Option type
        expire_time|str|Expiration date
        strike_price|str|Strike price
        contract_size|float|Contract size
        contract_multiplier|float|Contract multiplier
        exercise_type|str|Exercise type
        days_to_expiry|int|Days to expiry
        net_open_interest|str|Net open interest
        contract_value|str|Contract value
        equal_underlying|str|Equivalent underlying
        index_option_type|str|Index option type
        intrinsic_value|float|Intrinsic value
        time_value|float|Time value
        breakeven_point|list|Breakeven points
        dist_to_breakeven|list|Distance to breakeven
        prob_of_profit|float|Probability of profit  (This field is in percentage form, so 20 is equivalent to 20%.)
        seller_roi|str|Seller ROI  (This field is in percentage form, so 20 is equivalent to 20%.)
        mark_price|float|Mark price
        leverage_ratio|str|Leverage ratio
        effective_gearing|str|Effective gearing

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_option_strategy(code='HK.00700', option_strategy=OptionStrategyType.STRADDLE)
if ret == RET_OK:
    index=0
    print(data['legs'][index])
    ret2,data2 = quote_ctx.get_option_quote(data['legs'][index])
    if ret2 == RET_OK:
        print(data2)
    else:
        print("get_analysis,error:",data2)
else:
    print('error:', data)

quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
[OptionStrategyLeg(code=HK.TCH260522P330000, action=BUY, quantity=1.0), OptionStrategyLeg(code=HK.TCH260522C330000, action=BUY, quantity=1.0)]
    price  change_val  change_rate volume turnover high_price low_price mid_price open_price  last_close_price open_interest premium implied_volatility     delta     gamma      vega     theta       rho option_type expire_time strike_price  contract_size  contract_multiplier exercise_type  days_to_expiry net_open_interest contract_value equal_underlying index_option_type  intrinsic_value  time_value   breakeven_point             dist_to_breakeven  prob_of_profit seller_roi  mark_price leverage_ratio effective_gearing
0  131.65         0.0          0.0    N/A      N/A        N/A       N/A       N/A        N/A            131.65           N/A     N/A                N/A  0.974369  0.000797  0.019825 -0.785757  0.016246         N/A  2026-05-22          N/A          100.0                100.0           N/A               2               N/A            N/A              N/A               N/A            125.2        6.45  [199.56, 460.44]  [255.64, -5.240000000000009]        0.315418        N/A       130.4            N/A               N/A
```

:::tip API Restrictions
* Maximum 120 requests per 30 seconds.
:::

---

# Option Screening

`get_option_screen(request)`

* **Description**

    Option screening. Mixes underlying-property and option-property filters. Underlying-property and option-property filters cannot be applied together within the same group, so the SDK opens new filter groups as needed: by default each filter condition is AND-joined with the previous (a new group is opened); when `or_with_previous=True` is set explicitly and the indicator_type matches the previous condition, the new condition is OR-joined with it (same group).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    request|OptionScreenRequest|Option screening request object; market_categories must be passed at construction

    * OptionScreenRequest fields:

        Field|Type|Description
        :-|:-|:-
        market_categories|list[int]|Option market category list  (Elements come from OptMarketCategory: US_STOCK=0, US_INDEX=1, US_FUTURE=2, HK_STOCK=3, HK_INDEX=4, JP_STOCK=5, JP_INDEX=6. US_FUTURE / JP_STOCK / JP_INDEX will be supported later; currently the result is empty)
        page_from|int|Pagination start position  (Defaults to 0)
        page_count|int|Maximum results per page  (Defaults to 200)

    * Filter builder methods (by default each call automatically opens a new filter group AND-joined with previous conditions; with `or_with_previous=True` and a matching indicator_type, the new condition is OR-joined with the previous one in the same group. Underlying-property and option-property filters cannot be applied together within the same group):

        Method|Description
        :-|:-
        add_underlying_filter(indicator_type, values=None, lower=None, upper=None, plate_list=None, parent_plate_id=None, or_with_previous=False)|Underlying property filter  (indicator_type comes from [OptUnderlyingIndicator](./quote.md#6584). STOCK_LIST takes security code strings directly (e.g. "US.AAPL", "HK.00700"). IV / HV / IV_RANK / IV_PERCENTILE etc. take **decimal** values (30% as 0.3). PLATE(103) will return an error; do not use it for now)
        add_option_filter(indicator_type, values=None, lower=None, upper=None, or_with_previous=False)|Option property filter  (indicator_type comes from [OptIndicator](./quote.md#6840). DELTA / GAMMA / VEGA / THETA / RHO and probability indicators (e.g. ITM_PROBABILITY) take 0~1 decimals. PREMIUM(2021) only supports sort / retrieve, using it as a filter returns an error; BUY_BREAK_EVEN_POINT(3023) is deprecated, new code should use BUY_TO_BEP(3011))
        new_filter_group()|Manually start a new filter group  (Groups are AND-joined; conditions inside a group are OR-joined)
        add_sort(indicator_type, desc=False)|Sort  (desc=True for descending; ascending by default)
        add_option_retrieve(indicator_type)|Declare additional option fields to return  (If not called, default basic fields are returned)
        add_underlying_retrieve(indicator_type)|Declare underlying fields to return  (Only after calling this will the underlying dict in the response be populated)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>When ret == RET_OK, returns (last_page, all_count, DataFrame)</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, an error description is returned</td>
        </tr>
    </table>

    * Returned DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Option code
        option_name|str|Option name
        strike_price|float|Strike price
        strike_date|str|Strike date
        option_type|int|Call / Put  (1=CALL, 2=PUT)
        exercise_type|int|Exercise type  (1=American, 2=European)
        expiration_type|int|Expiration type  (1=Weekly, 2=Monthly, 3=Quarterly)
        in_the_money|bool|Whether in the money
        left_day|int|Days remaining
        price|float|Option price
        mid_price|float|Mid price
        bid_price|float|Bid price
        ask_price|float|Ask price
        bid_ask_spread|float|Bid-ask spread
        bid_volume|int|Bid volume
        ask_volume|int|Ask volume
        bid_ask_volume_ratio|float|Bid-ask volume ratio
        change_ratio|float|Change ratio
        volume|int|Volume
        turnover|float|Turnover
        open_interest|int|Open interest
        open_interest_market_cap|float|Open interest market cap
        vol_oi_ratio|float|Volume / open interest ratio
        premium|float|Premium
        implied_volatility|float|Implied volatility
        history_volatility|float|Historical volatility
        iv_hv_ratio|float|IV/HV
        delta|float|Greeks Delta
        gamma|float|Greeks Gamma
        vega|float|Greeks Vega
        theta|float|Greeks Theta
        rho|float|Greeks Rho
        leverage_ratio|float|Leverage ratio
        effective_gearing|float|Effective leverage
        itm_probability|float|In-the-money probability
        buy_to_bep|float|Buy-to-break-even ratio
        sell_to_bep|float|Sell-to-break-even ratio
        buy_profit_probability|float|Buy profit probability
        sell_profit_probability|float|Sell profit probability
        intrinsic_value_per|float|Intrinsic value percentage
        time_value_per|float|Time value percentage
        itm_degree|float|In-the-money degree
        otm_degree|float|Out-of-the-money degree
        otm_probability|float|Out-of-the-money probability
        sell_annualized_return|float|Sell annualized return
        interval_return|float|Sell interval return
        underlying|dict|Underlying info (returned only when add_underlying_retrieve is called)  (dict contains stock_id / iv / hv / iv_rank / iv_percentile / market_cap / price / change_ratio)

* **Example**

```python
from moomoo import (
    OpenQuoteContext, RET_OK, OptionScreenRequest,
    OptMarketCategory, OptIndicator, OptUnderlyingIndicator,
)

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Example 1: US underlyings with IV>30% + near-the-money CALL
req = OptionScreenRequest(market_categories=[OptMarketCategory.US_STOCK])
req.add_underlying_filter(OptUnderlyingIndicator.IV, lower=0.3)              # Underlying IV >= 30% (decimal)
req.add_option_filter(OptIndicator.OPTION_TYPE, values=[1])                  # CALL
req.add_option_filter(OptIndicator.DELTA, lower=0.3, upper=0.7)              # Delta 0.3~0.7
req.add_option_filter(OptIndicator.LEFT_DAY, lower=7, upper=60)              # 7~60 days remaining
req.add_sort(OptIndicator.VOLUME, desc=True)                                 # Volume descending
req.add_option_retrieve(OptIndicator.DELTA)
req.add_option_retrieve(OptIndicator.VOLUME)
req.page_count = 30

ret, data = quote_ctx.get_option_screen(req)
if ret == RET_OK:
    last_page, all_count, df = data
    print(df[['code', 'option_name', 'delta', 'volume']].head(10))
else:
    print('error: ', data)

# Example 2: HK options for a specific underlying + return underlying info
# Note: STOCK_LIST takes security code strings directly (e.g. "HK.00700", "US.AAPL").
req = OptionScreenRequest(market_categories=[OptMarketCategory.HK_STOCK])
req.add_underlying_filter(OptUnderlyingIndicator.STOCK_LIST,
                          values=["HK.00700"])                                # Underlying = Tencent
req.add_option_filter(OptIndicator.OPTION_TYPE, values=[1])                   # CALL
req.add_option_filter(OptIndicator.OPTION_TYPE, values=[2],
                      or_with_previous=True)                                  # OR with previous: CALL + PUT
req.add_underlying_retrieve(OptUnderlyingIndicator.IV)
req.add_underlying_retrieve(OptUnderlyingIndicator.MARKET_CAP)
req.add_sort(OptIndicator.OPEN_INTEREST, desc=True)                           # Open interest descending
req.page_count = 50

ret, data = quote_ctx.get_option_screen(req)
if ret == RET_OK:
    last_page, all_count, df = data
    print(df[['code', 'option_name', 'option_type', 'open_interest', 'underlying']].head(10))
else:
    print('error: ', data)

quote_ctx.close()
```

* **Output**

```python
# Example 1:
                   code          option_name    delta  volume
0      US.GT260717C7000      GT 260717 7.00C  0.33809   38831
1  US.INTC260717C150000  INTC 260717 150.00C  0.30582   19548
2   US.MU260626C1050000   MU 260626 1050.00C  0.43334   18949
3  US.TSLA260710C400000  TSLA 260710 400.00C  0.58114   16002
4  US.CRWV260717C120000  CRWV 260717 120.00C  0.30415   15932
5    US.COMP260717C9000    COMP 260717 9.00C  0.47409   15645
6    US.SLV260717C65500    SLV 260717 65.50C  0.35809   13291
7  US.TSLA260710C410000  TSLA 260710 410.00C  0.50861   13010
8    US.SPCE260717C5000    SPCE 260717 5.00C  0.41268   12701
9  US.HOOD260717C100000  HOOD 260717 100.00C  0.41248   12572

# Example 2:
                  code         option_name  option_type  open_interest                                         underlying
0  HK.TCH260730C610000  腾讯 260730 610.00 购            1          70474  {'stock_id': 54047868453564, 'iv': 0.36337, 'h...
1  HK.TCH260629C500000  腾讯 260629 500.00 购            1          56334  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
2  HK.TCH260929C550000  腾讯 260929 550.00 购            1          46470  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
3  HK.TCH260730C520000  腾讯 260730 520.00 购            1          44071  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
4  HK.TCH260929C650000  腾讯 260929 650.00 购            1          38316  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
5  HK.TCH260629C530000  腾讯 260629 530.00 购            1          34532  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
6  HK.TCH260629C540000  腾讯 260629 540.00 购            1          34085  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
7  HK.TCH270330P230000  腾讯 270330 230.00 沽            2          30586  {'stock_id': 54047868453564, 'iv': 0.36337, 'h...
8  HK.TCH270330C230000  腾讯 270330 230.00 购            1          30000  {'stock_id': 54047868453564, 'iv': 0.36337, 'h...
9  HK.TCH260629C600000  腾讯 260629 600.00 购            1          27394  {'stock_id': 54047868453564, 'iv': 0.36406, 'h...
```

* **Per-field examples (by category)**

    > All examples below assume the US_STOCK market: first `req = OptionScreenRequest(market_categories=[OptMarketCategory.US_STOCK])`,
    > then stack the filter / retrieve / sort conditions from each section, and finally `quote_ctx.get_option_screen(req)` to obtain `(last_page, all_count, df)`.
    > The measured `head` is taken directly from the returned DataFrame; the `underlying.<field>` column in the underlying-property examples is expanded by `add_underlying_retrieve(...)`.

    #### Underlying properties (OptUnderlyingIndicator)

    Passed via `add_underlying_filter(indicator_type, lower, upper, values, ...)`. Percentage indicators such as IV/HV/IV_RANK take **decimal values** (30% as 0.3), and `add_underlying_retrieve(...)` is required for values to appear in the `underlying` dict

    ##### `IV`（id=203 · interval · OptUnderlyingIndicator） Underlying implied volatility

    Unit: %; SDK takes decimals directly (30% as 0.3). add_underlying_retrieve is required for the value to show up in the underlying dict

    ```python
    req.add_underlying_filter(OptUnderlyingIndicator.IV, lower=0.3)
    req.add_underlying_retrieve(OptUnderlyingIndicator.IV)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=1456207, 10 rows matched, head top 5):

    ```
                    code          option_name  volume  underlying.iv
    US.NVDA260612C205000  NVDA 260612 205.00C  226041        0.45135
    US.NVDA260612P200000  NVDA 260612 200.00P  184565        0.45135
    US.NVDA260612C202500  NVDA 260612 202.50C  163991        0.45135
    US.NVDA260612C210000  NVDA 260612 210.00C  147236        0.45135
    US.NVDA260612C207500  NVDA 260612 207.50C  143944        0.45135
    ```

    ##### `HV`（id=204 · interval · OptUnderlyingIndicator） Underlying historical volatility

    Unit: %; SDK takes decimals directly

    ```python
    req.add_underlying_filter(OptUnderlyingIndicator.HV, lower=0.3)
    req.add_underlying_retrieve(OptUnderlyingIndicator.HV)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=1336194, 10 rows matched, head top 5):

    ```
                    code          option_name  volume  underlying.hv
    US.NVDA260612C205000  NVDA 260612 205.00C  226041        0.46845
    US.NVDA260612P200000  NVDA 260612 200.00P  184565        0.46845
    US.NVDA260612C202500  NVDA 260612 202.50C  163991        0.46845
    US.NVDA260612C210000  NVDA 260612 210.00C  147236        0.46845
    US.NVDA260612C207500  NVDA 260612 207.50C  143944        0.46845
    ```

    ##### `IV_RANK`（id=205 · interval · OptUnderlyingIndicator） Underlying IV rank

    0~100; measures the relative position of the current IV in its historical range

    ```python
    req.add_underlying_filter(OptUnderlyingIndicator.IV_RANK, lower=50.0)
    req.add_underlying_retrieve(OptUnderlyingIndicator.IV_RANK)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=0, 0 rows matched): no data. Reason: No data in the OpenD sample; can lower the threshold and retry

    ##### `MARKET_CAP`（id=401 · interval · OptUnderlyingIndicator） Underlying market cap

    Unit: in currency; SDK takes the raw value (10 billion as 10_000_000_000)

    ```python
    req.add_underlying_filter(OptUnderlyingIndicator.MARKET_CAP, lower=100_000_000_000.0)
    req.add_underlying_retrieve(OptUnderlyingIndicator.MARKET_CAP)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=357921, 10 rows matched, head top 5):

    ```
                    code          option_name  volume  underlying.market_cap
    US.NVDA260612C205000  NVDA 260612 205.00C  226041        4957854000000.0
    US.NVDA260612P200000  NVDA 260612 200.00P  184565        4957854000000.0
    US.NVDA260612C202500  NVDA 260612 202.50C  163991        4957854000000.0
    US.NVDA260612C210000  NVDA 260612 210.00C  147236        4957854000000.0
    US.NVDA260612C207500  NVDA 260612 207.50C  143944        4957854000000.0
    ```

    ##### `STOCK_PRICE`（id=402 · interval · OptUnderlyingIndicator） Underlying price

    Unit: in currency; SDK takes the raw price directly

    ```python
    req.add_underlying_filter(OptUnderlyingIndicator.STOCK_PRICE, lower=50.0, upper=500.0)
    req.add_underlying_retrieve(OptUnderlyingIndicator.STOCK_PRICE)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=1055665, 10 rows matched, head top 5):

    ```
                    code          option_name  volume  underlying.price
    US.NVDA260612C205000  NVDA 260612 205.00C  226041            204.87
    US.NVDA260612P200000  NVDA 260612 200.00P  184565            204.87
    US.NVDA260612C202500  NVDA 260612 202.50C  163991            204.87
    US.NVDA260612C210000  NVDA 260612 210.00C  147236            204.87
    US.NVDA260612C207500  NVDA 260612 207.50C  143944            204.87
    ```

    #### Option properties (OptIndicator)

    Passed via `add_option_filter(indicator_type, lower, upper, values, ...)`. Greeks (DELTA/GAMMA/THETA/VEGA/RHO) and probability indicators (ITM_PROBABILITY etc.) take **0~1 decimal values**

    ##### `STRIKE_PRICE`（id=1001 · interval · OptIndicator） Strike price

    Unit: in currency; SDK takes the raw price directly

    ```python
    req.add_option_filter(OptIndicator.STRIKE_PRICE, lower=50.0, upper=100.0)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=400354, 10 rows matched, head top 5):

    ```
                   code         option_name  strike_price  volume
     US.HYG260717P75000   HYG 260717 75.00P          75.0   72679
     US.BAC260618C55000   BAC 260618 55.00C          55.0   55636
    US.TQQQ260612P72000  TQQQ 260612 72.00P          72.0   43326
     US.IEF260618C95000   IEF 260618 95.00C          95.0   42077
     US.HYG260918P75000   HYG 260918 75.00P          75.0   42012
    ```

    ##### `LEFT_DAY`（id=1002 · interval · OptIndicator） Days to expiration

    Unit: days; integer. Near-month is typically < 30

    ```python
    req.add_option_filter(OptIndicator.LEFT_DAY, lower=7, upper=60)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=553649, 10 rows matched, head top 5):

    ```
                   code         option_name  left_day  volume
     US.HYG260717P75000   HYG 260717 75.00P        35   72679
    US.POET260717P17000  POET 260717 17.00P        35   60754
     US.HYG260717P78000   HYG 260717 78.00P        35   40594
     US.HYG260717P79000   HYG 260717 79.00P        35   34919
     US.IEF260717P93000   IEF 260717 93.00P        35   34807
    ```

    ##### `OPTION_TYPE`（id=1003 · values · OptIndicator） Call/Put

    Enum: 1=CALL, 2=PUT; values takes an enum array

    ```python
    req.add_option_filter(OptIndicator.OPTION_TYPE, values=[1])  # CALL
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=972181, 10 rows matched, head top 5):

    ```
                    code          option_name  option_type  volume
    US.NVDA260612C205000  NVDA 260612 205.00C            1  226041
    US.NVDA260612C202500  NVDA 260612 202.50C            1  163991
    US.NVDA260612C210000  NVDA 260612 210.00C            1  147236
    US.NVDA260612C207500  NVDA 260612 207.50C            1  143944
     US.SPY260612C740000   SPY 260612 740.00C            1  114906
    ```

    ##### `IN_THE_MONEY`（id=2001 · values · OptIndicator） In the money or not

    Enum: 1=ITM, 0=OTM

    ```python
    req.add_option_filter(OptIndicator.IN_THE_MONEY, values=[1])  # 仅价内
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=972389, 10 rows matched, head top 5):

    ```
                    code          option_name  in_the_money  volume
    US.NVDA260612C202500  NVDA 260612 202.50C             1  163991
    US.AAPL260612C295000  AAPL 260612 295.00C             1   87879
     US.SPY260612C735000   SPY 260612 735.00C             1   77126
    US.TSLA260612C390000  TSLA 260612 390.00C             1   70408
     US.SPY260612C730000   SPY 260612 730.00C             1   62881
    ```

    ##### `PRICE`（id=2002 · interval · OptIndicator） Option price

    Unit: in currency; SDK takes the raw price directly

    ```python
    req.add_option_filter(OptIndicator.PRICE, lower=1.0, upper=10.0)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=644732, 10 rows matched, head top 5):

    ```
                    code          option_name  price  volume
    US.NVDA260612C205000  NVDA 260612 205.00C    2.0  226041
    US.NVDA260612C202500  NVDA 260612 202.50C   3.55  163991
    US.NVDA260612C207500  NVDA 260612 207.50C   1.04  143944
     US.SPY260612C740000   SPY 260612 740.00C   2.97  114906
    US.TSLA260612C400000  TSLA 260612 400.00C   6.45   93756
    ```

    ##### `VOLUME`（id=2011 · interval · OptIndicator） Volume

    Unit: contracts

    ```python
    req.add_option_filter(OptIndicator.VOLUME, lower=1000)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=8010, 10 rows matched, head top 5):

    ```
                    code          option_name  volume
    US.NVDA260612C205000  NVDA 260612 205.00C  226041
    US.NVDA260612P200000  NVDA 260612 200.00P  184565
    US.NVDA260612C202500  NVDA 260612 202.50C  163991
    US.NVDA260612C210000  NVDA 260612 210.00C  147236
    US.NVDA260612C207500  NVDA 260612 207.50C  143944
    ```

    ##### `OPEN_INTEREST`（id=2013 · interval · OptIndicator） Open interest

    Unit: contracts

    ```python
    req.add_option_filter(OptIndicator.OPEN_INTEREST, lower=1000)
    req.add_sort(OptIndicator.OPEN_INTEREST, desc=True)
    ```

    Measured response (US_STOCK · all_count=92911, 10 rows matched, head top 5):

    ```
                   code         option_name  open_interest
     US.HYG260618P79000   HYG 260618 79.00P         451310
    US.BKLN260717P20000  BKLN 260717 20.00P         406177
     US.HYG261120C81000   HYG 261120 81.00C         386200
     US.HYG260618P77000   HYG 260618 77.00P         332022
     US.HYG260618P75000   HYG 260618 75.00P         324096
    ```

    ##### `IMPLIED_VOLATILITY`（id=3001 · interval · OptIndicator） Implied volatility

    Unit: %; SDK takes decimals directly (50% as 0.5)

    ```python
    req.add_option_filter(OptIndicator.IMPLIED_VOLATILITY, lower=0.3)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=1480382, 10 rows matched, head top 5):

    ```
                    code          option_name  implied_volatility  volume
    US.NVDA260612C205000  NVDA 260612 205.00C             0.70232  226041
    US.NVDA260612P200000  NVDA 260612 200.00P             0.77927  184565
    US.NVDA260612C202500  NVDA 260612 202.50C             0.72661  163991
    US.NVDA260612C210000  NVDA 260612 210.00C             0.76536  147236
    US.NVDA260612C207500  NVDA 260612 207.50C             0.72576  143944
    ```

    ##### `DELTA`（id=3004 · interval · OptIndicator） Greeks Delta

    CALL∈[0,1], PUT∈[-1,0]; SDK takes decimals directly

    ```python
    req.add_option_filter(OptIndicator.DELTA, lower=0.3, upper=0.7)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=219233, 10 rows matched, head top 5):

    ```
                    code          option_name    delta  volume
    US.NVDA260612C205000  NVDA 260612 205.00C  0.49538  226041
    US.NVDA260612C202500  NVDA 260612 202.50C  0.68114  163991
    US.NVDA260612C207500  NVDA 260612 207.50C  0.31335  143944
     US.SPY260612C740000   SPY 260612 740.00C  0.45037  114906
    US.TSLA260612C400000  TSLA 260612 400.00C  0.48887   93756
    ```

    ##### `GAMMA`（id=3005 · interval · OptIndicator） Greeks Gamma

    ≥0; SDK takes decimals directly

    ```python
    req.add_option_filter(OptIndicator.GAMMA, lower=0.01)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=810281, 10 rows matched, head top 5):

    ```
                    code          option_name    gamma  volume
    US.NVDA260612C205000  NVDA 260612 205.00C  0.07901  226041
    US.NVDA260612P200000  NVDA 260612 200.00P   0.0477  184565
    US.NVDA260612C202500  NVDA 260612 202.50C  0.06835  163991
    US.NVDA260612C210000  NVDA 260612 210.00C   0.0481  147236
    US.NVDA260612C207500  NVDA 260612 207.50C  0.06793  143944
    ```

    ##### `THETA`（id=3007 · interval · OptIndicator） Greeks Theta

    Typically ≤0 (time decay); SDK takes decimals directly

    ```python
    req.add_option_filter(OptIndicator.THETA, upper=-0.01)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=1238755, 10 rows matched, head top 5):

    ```
                    code          option_name     theta  volume
    US.NVDA260612C205000  NVDA 260612 205.00C  -2.30979  226041
    US.NVDA260612P200000  NVDA 260612 200.00P  -1.67055  184565
    US.NVDA260612C202500  NVDA 260612 202.50C  -2.13163  163991
    US.NVDA260612C210000  NVDA 260612 210.00C  -1.62903  147236
    US.NVDA260612C207500  NVDA 260612 207.50C  -2.10361  143944
    ```

    ##### `ITM_PROBABILITY`（id=3019 · interval · OptIndicator） ITM probability

    0~1 decimal; SDK takes the value as-is

    ```python
    req.add_option_filter(OptIndicator.ITM_PROBABILITY, lower=0.3, upper=0.7)
    req.add_sort(OptIndicator.VOLUME, desc=True)
    ```

    Measured response (US_STOCK · all_count=417899, 10 rows matched, head top 5):

    ```
                    code          option_name  itm_probability  volume
    US.NVDA260612C205000  NVDA 260612 205.00C          0.48389  226041
     US.SPY260612C740000   SPY 260612 740.00C          0.36646  114906
    US.TSLA260612C400000  TSLA 260612 400.00C          0.46733   93756
    US.AAPL260612C295000  AAPL 260612 295.00C          0.57372   87879
     US.SPY260612C735000   SPY 260612 735.00C          0.66411   77126
    ```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Option Market Statistics

`get_option_market_statistic(option_market, data_type, begin_time=None, end_time=None, page_req_key=None)`

* **Description**

    Get option market statistics (volume/open interest), returns call, put, and total values by trading day granularity, with pagination support.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    option_market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, US_INDEX=US index options, HK_SECURITY=HK equity options, HK_INDEX=HK index options)
    data_type|[OptionStatisticDataType](./quote.md#4529)|Data type  (VOLUME=Volume, OPEN_INTEREST=Open interest)
    begin_time|str|Start date, format 'YYYY-MM-DD'  (If not specified, defaults to data from the past year)
    end_time|str|End date, format 'YYYY-MM-DD'  (Time span with begin_time must not exceed one year)
    page_req_key|bytes|Pagination request key  (Pass None for the first request, pass the previously returned value for subsequent requests)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns statistics data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
        <tr>
            <td>page_req_key</td>
            <td>bytes</td>
            <td>Next page key, None indicates no more data</td>
        </tr>
    </table>

    * Returned DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        time|str|Trading day time string
        timestamp|float|Trading day timestamp (Unix seconds)
        call_value|int|Call option total value
        put_value|int|Put option total value
        total_value|int|Total value (call_value + put_value)
        ratio|float|Put/Call ratio  (N/A when call_value is 0)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, page_req_key = quote_ctx.get_option_market_statistic(
    OptionMarket.US_SECURITY,
    OptionStatisticDataType.VOLUME,
    begin_time='2026-06-01',
    end_time='2026-06-15'
)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
         time     timestamp  call_value  put_value  total_value     ratio
0  2026-06-12  1.781237e+09    45658870   28723978     74382848  0.629100
1  2026-06-11  1.781150e+09    38303062   30520043     68823105  0.796804
2  2026-06-10  1.781064e+09    35371830   30180004     65551834  0.853221
3  2026-06-09  1.780978e+09    42880655   36646152     79526807  0.854608
4  2026-06-08  1.780891e+09    35442266   25811533     61253799  0.728270
5  2026-06-05  1.780632e+09    52362998   44023321     96386319  0.840733
6  2026-06-04  1.780546e+09    38082169   24572137     62654306  0.645240
7  2026-06-03  1.780459e+09    36858233   23035404     59893637  0.624973
8  2026-06-02  1.780373e+09    36822706   21026201     57848907  0.571012
9  2026-06-01  1.780286e+09    42932185   24084036     67016221  0.560979
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the option market statistics interface (for paginated interfaces, only the first call counts)
:::

---

# Option Underlying Overview

`get_option_underlying_overview(code_list, index_option_type=IndexOptionType.NORMAL)`

* **Description**

    Batch retrieve option underlying overview data, including the latest snapshot of core metrics such as volume, open interest, implied volatility (IV), and multi-period historical volatility (HV).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code_list|list[str]|List of underlying stock codes  (e.g. ['US.AAPL', 'US.TSLA'], max 500)
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type  (NORMAL=standard options (default), SMALL=mini index options, only needed for HSI/HSCEI)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns underlying overview data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Stock code
        name|str|Underlying name
        call_volume|int|Call option volume
        put_volume|int|Put option volume
        call_open_interest|int|Call option open interest (T-1 delayed)
        put_open_interest|int|Put option open interest (T-1 delayed)
        iv|float|Implied volatility (percentage)
        iv_rank|float|IV rank percentile (percentage)
        iv_percentile|float|IV percentile (percentage)
        pre_iv|float|Previous trading day IV (percentage)
        hv_30d|float|30-day historical volatility (percentage)
        hv_30d_percentile|float|30-day HV percentile
        hv_60d|float|60-day historical volatility (percentage)
        hv_60d_percentile|float|60-day HV percentile
        hv_90d|float|90-day historical volatility (percentage)
        hv_90d_percentile|float|90-day HV percentile
        hv_120d|float|120-day historical volatility (percentage)
        hv_120d_percentile|float|120-day HV percentile
        hv_365d|float|365-day historical volatility (percentage)
        hv_365d_percentile|float|365-day HV percentile

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_underlying_overview(['US.AAPL', 'US.TSLA', 'US.NVDA'])
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
      code  name  call_volume  put_volume  call_open_interest  put_open_interest      iv  iv_rank  iv_percentile  pre_iv  hv_30d  hv_30d_percentile  hv_60d  hv_60d_percentile  hv_90d  hv_90d_percentile  hv_120d  hv_120d_percentile  hv_365d  hv_365d_percentile
0  US.AAPL  Apple       782941      490299             3165108            2237950  25.126   37.702         19.841  25.617  23.324             59.126  24.641             65.476  23.019             46.825   23.582              47.619   22.619               8.333
1  US.TSLA  Tesla      2197764     1425740             4178685            2909774  55.053   39.265         64.285  55.401  49.359             68.254  46.536             58.730  44.990             46.031   41.688              29.761   44.500               1.190
2  US.NVDA  NVIDIA     1980405     1176926             9096278            7648683  41.975   27.062         42.460  45.135  45.921             96.825  42.646             99.206  39.980             92.460   38.971              81.746   34.989              17.063
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds
:::

---

# Option Underlying Historical Statistics

`get_option_underlying_his_statistic(code, index_option_type=IndexOptionType.NORMAL, begin_time=None, end_time=None, page_req_key=None)`

* **Description**

    Get option underlying historical statistics data, returning daily time series of volume, open interest, and Put/Call ratios for the underlying's options, with pagination support.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Underlying stock code  (e.g. 'US.AAPL')
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type  (NORMAL=standard options (default), SMALL=mini index options)
    begin_time|str|Start date, format 'YYYY-MM-DD'  (Defaults to 364 days before end_time if not provided)
    end_time|str|End date, format 'YYYY-MM-DD'  (Max span of 364 days from begin_time)
    page_req_key|bytes|Pagination request key  (Pass None for first call, pass previous return value for subsequent calls)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns statistics data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
        <tr>
            <td>page_req_key</td>
            <td>bytes</td>
            <td>Next page key, None indicates no more data</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Stock code
        name|str|Stock name
        time|str|Trading day time string
        timestamp|float|Trading day timestamp (Unix seconds)
        option_volume|int|Total option volume (call_volume + put_volume)
        call_volume|int|Call option volume
        put_volume|int|Put option volume
        put_call_volume_ratio|float|Put/Call volume ratio
        option_open_interest|int|Total option open interest
        call_open_interest|int|Call option open interest (T-1 delayed)
        put_open_interest|int|Put option open interest (T-1 delayed)
        put_call_open_interest_ratio|float|Put/Call open interest ratio
        underlying_price|float|Underlying price

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, page_req_key = quote_ctx.get_option_underlying_his_statistic(
    'US.AAPL',
    begin_time='2026-06-01',
    end_time='2026-06-15'
)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
      code  name        time     timestamp  option_volume  call_volume  put_volume  put_call_volume_ratio  option_open_interest  call_open_interest  put_open_interest put_call_open_interest_ratio  underlying_price
0  US.AAPL  Apple  2026-06-12  1.781237e+09        1273240       782941      490299               0.626227                     0                   0                  0                          N/A            291.13
1  US.AAPL  Apple  2026-06-11  1.781150e+09         950737       580535      370202               0.637691               5403058             3165108            2237950                     0.707069            295.63
2  US.AAPL  Apple  2026-06-10  1.781064e+09        1734799      1039630      695169               0.668670               5522747             3270454            2252293                     0.688679            291.58
3  US.AAPL  Apple  2026-06-09  1.780978e+09        1715749      1024046      691703               0.675461               5405022             3209586            2195436                     0.684025            290.55
4  US.AAPL  Apple  2026-06-08  1.780891e+09        2179789      1293656      886133               0.684983               5350402             3142828            2207574                     0.702416            301.54
...
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds (for paginated interfaces, only the first call counts)
:::

---

# Option Underlying Historical Volatility

`get_option_underlying_his_volatility(code, index_option_type=IndexOptionType.NORMAL, begin_time=None, end_time=None, page_req_key=None)`

* **Description**

    Get option underlying historical volatility data, returning daily IV and HV time series along with the underlying's closing price, with pagination support.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Underlying stock code  (e.g. 'US.AAPL')
    index_option_type|[IndexOptionType](./quote.md#2866)|Index option type  (NORMAL=standard options (default), SMALL=mini index options)
    begin_time|str|Start date, format 'YYYY-MM-DD'
    end_time|str|End date, format 'YYYY-MM-DD'
    page_req_key|bytes|Pagination request key  (Pass None for first call, pass previous return value for subsequent calls)

    :::tip Time Range
    - Maximum span between `begin_time` and `end_time` is **364 days**
    - Both empty: `end_time` = today, `begin_time` = today minus 364 days
    - Only `begin_time` provided: `end_time` = `begin_time` plus 364 days
    - Only `end_time` provided: `begin_time` = `end_time` minus 364 days
    :::

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns volatility data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
        <tr>
            <td>page_req_key</td>
            <td>bytes</td>
            <td>Next page key, None indicates no more data</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Stock code
        name|str|Stock name
        time|str|Trading day time string
        timestamp|float|Trading day timestamp (Unix seconds)
        iv|float|Implied volatility (percentage)
        hv|float|Historical volatility (percentage)
        underlying_price|float|Underlying closing price (mark price for current day)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, page_req_key = quote_ctx.get_option_underlying_his_volatility(
    'US.AAPL',
    begin_time='2026-06-01',
    end_time='2026-06-15'
)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
      code  name        time     timestamp      iv      hv  underlying_price
0  US.AAPL  Apple  2026-06-12  1.781237e+09  25.126  23.324            291.13
1  US.AAPL  Apple  2026-06-11  1.781150e+09  25.617  23.270            295.63
2  US.AAPL  Apple  2026-06-10  1.781064e+09  27.384  22.892            291.58
3  US.AAPL  Apple  2026-06-09  1.780978e+09  27.237  22.854            290.55
4  US.AAPL  Apple  2026-06-08  1.780891e+09  26.368  19.028            301.54
5  US.AAPL  Apple  2026-06-05  1.780632e+09  26.995  18.024            307.34
6  US.AAPL  Apple  2026-06-04  1.780546e+09  25.249  17.366            311.23
7  US.AAPL  Apple  2026-06-03  1.780459e+09  26.801  18.927            310.26
8  US.AAPL  Apple  2026-06-02  1.780373e+09  26.258  18.415            315.20
9  US.AAPL  Apple  2026-06-01  1.780286e+09  25.864  16.841            306.31
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds (for paginated interfaces, only the first call counts)
:::

---

# Option Underlying Rank

`get_option_underlying_rank(option_market, sort_type, sort_direction=None, count=None, trading_date=None, filter_list=None, page=None)`

* **Description**

    Get option underlying ranking. Ranks option underlyings (stocks/ETFs/indices) by the specified dimension, with support for multi-dimensional filtering and pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    option_market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, US_INDEX=US index options, HK_SECURITY=HK equity options, HK_INDEX=HK index options)
    sort_type|[UnderlyingRankSortType](./quote.md#7252)|Sort field  (VOLUME=Total volume, VOLUME_RATIO=Put/Call volume ratio, OPEN_INTEREST=Total open interest, OPEN_INTEREST_RATIO=Put/Call OI ratio, PRICE=Latest price, PRICE_CHANGE=Price change, IV=IV, IV_CHANGE=IV change, HV=HV, HV_CHANGE=HV change, IV_RANK=IV Rank, IV_PERCENTILE=IV Percentile, MARKET_CAP=Market cap)
    sort_direction|int|Sort direction  (0=Descending (default), 1=Ascending)
    count|int|Page size  (Range [1,200], default 200)
    trading_date|str|Trading date  (Format yyyy-MM-dd, returns latest ranking if not specified)
    filter_list|list[UnderlyingRankFilter]|Filter conditions list  (Multiple conditions are combined with AND logic)
    page|str|Pagination cursor  (Pass None for the first request, pass the previously returned next_page for subsequent pages)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns ranking data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
        <tr>
            <td>next_page</td>
            <td>str</td>
            <td>Next page cursor string, None indicates no more pages</td>
        </tr>
        <tr>
            <td>all_count</td>
            <td>int</td>
            <td>Total count of records matching the filter conditions</td>
        </tr>
    </table>

    * data DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Underlying stock code
        name|str|Underlying name
        total_volume|int|Total option volume
        total_open_interest|int|Total option open interest
        volume_ratio|float|Put/Call volume ratio (percentage)
        open_interest_ratio|float|Put/Call open interest ratio (percentage)
        iv|float|Implied volatility (percentage)
        iv_rank|float|IV rank percentile (percentage)
        iv_percentile|float|IV percentile (percentage)
        price|float|Underlying latest price
        change_ratio|float|Underlying price change ratio (decimal)
        iv_change|float|IV change rate (percentage)
        hv|float|Historical volatility (percentage)
        hv_change|float|HV change rate (percentage)
        market_cap|float|Market capitalization
        trading_date|str|Trading date of the ranking data
        trading_timestamp|float|Trading date timestamp of the ranking data (Unix seconds)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_option_underlying_rank(
    option_market=OptionMarket.US_SECURITY,
    sort_type=UnderlyingRankSortType.VOLUME,
    count=5
)
if ret == RET_OK:
    print(data)
    print('all_count:', all_count)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
      code                        name  total_volume  total_open_interest  volume_ratio  open_interest_ratio      iv  iv_rank  iv_percentile   price  change_ratio  iv_change      hv  hv_change    market_cap trading_date  trading_timestamp
0   US.SPY               标普500ETF-SPDR      14228830             19909256       0.97899              1.93868  17.675   27.143         61.111  741.75      0.540826     -8.261  15.031     -0.057  7.814945e+11   2026-06-12       1.781237e+09
1   US.QQQ  纳指100ETF-Invesco QQQ Trust       8239190             12964422       0.99417              1.49888  27.652   62.918         91.269  721.34      0.588465     -8.332  26.196     -0.644  4.765533e+11   2026-06-12       1.781237e+09
2  US.TSLA                         特斯拉       3623504              7088459       0.64872              0.69633  55.053   39.265         64.285  406.43      1.823876     -0.629  49.359     -1.194  1.526439e+12   2026-06-12       1.781237e+09
3  US.NVDA                         英伟达       3157331             16744961       0.59428              0.84085  41.975   27.062         42.460  205.19      0.156197     -7.002  45.921     -1.972  4.965598e+12   2026-06-12       1.781237e+09
4   US.IWM           罗素2000ETF-iShares       2840729             11791964       0.79034              2.78276  24.857   33.930         64.285  292.95      0.874626     -6.744  24.802      0.522  8.061984e+10   2026-06-12       1.781237e+09
all_count: 6017
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the option underlying rank interface (for paginated interfaces, only the first call counts)
:::

---

# Option Contract Rank

`get_option_rank(option_market, sort_type, count=None, trading_date=None, sort_direction=None, page=None, filter_list=None)`

* **Description**

    Get option contract ranking list, supports sorting by volume, open interest, OI increment, OI decrement, IV, change rate, and other dimensions.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    option_market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, US_INDEX=US index options, HK_SECURITY=HK equity options, HK_INDEX=HK index options)
    sort_type|[OptionRankType](./quote.md#325)|Sort type  (VOLUME=Volume, TURNOVER=Turnover, OI=Open interest, OI_INCREMENT=OI increment(daily), OI_DECREMENT=OI decrement(daily), OI_MARKET_CAP=OI market cap, OI_MARKET_CAP_INCREMENT=OI market cap increment(daily), OI_MARKET_CAP_DECREMENT=OI market cap decrement(daily), CHANGE_RATE=Price change rate, IV=Implied volatility)
    count|int|Return count  (Range [1,200], default 200)
    trading_date|str|Trading date  (Format yyyy-MM-dd, returns latest ranking if not specified)
    sort_direction|int|Sort direction  (0=descending(default), 1=ascending)
    page|str|Pagination cursor  (Omit for the first request, pass next_page for subsequent pages)
    filter_list|list[OptionRankFilter]|Filter conditions list  (Multiple conditions are combined with AND logic)

* **Returns**

    Returns a 4-tuple (ret, data, next_page, all_count)

    Parameter|Type|Description
    :-|:-|:-
    ret|[RET_CODE](../ftapi/common.html#7467)|Interface call result
    data|pandas.DataFrame|When ret == RET_OK, returns ranking data
    data|str|When ret != RET_OK, returns error description
    next_page|str|Pagination cursor for next page, None means no more data
    all_count|int|Total count matching filter conditions

    * data DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        code|str|Option contract code
        name|str|Option name
        option_type|str|Option type  (CALL/PUT)
        oi_increment|int|OI increment (>=0)
        oi_decrement|int|OI decrement (>=0)
        oi_market_cap_increment|float|OI market cap increment (>=0)
        oi_market_cap_decrement|float|OI market cap decrement (>=0)
        volume|int|Volume
        turnover|float|Turnover
        open_interest|int|Open interest
        open_interest_market_cap|float|Open interest market cap
        iv|float|Implied volatility (percentage)
        option_price|float|Option latest price
        change_ratio|float|Price change ratio (decimal)
        mid_price|float|Mid price
        bid_price|float|Bid price
        bid_volume|int|Bid volume
        ask_price|float|Ask price
        ask_volume|int|Ask volume
        delta|float|Delta
        gamma|float|Gamma
        theta|float|Theta
        vega|float|Vega
        rho|float|Rho
        trading_date|str|Trading date of ranking data
        trading_timestamp|float|Trading date timestamp (Unix seconds)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_option_rank(
    OptionMarket.US_SECURITY,
    OptionRankType.VOLUME,
    count=5
)
if ret == RET_OK:
    print(data)
    print('all_count:', all_count)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
                  code                name option_type  oi_increment oi_decrement  oi_market_cap_increment oi_market_cap_decrement  volume    turnover  open_interest  open_interest_market_cap       iv  option_price  change_ratio  mid_price  bid_price  bid_volume  ask_price  ask_volume    delta    gamma      theta     vega  rho trading_date  trading_timestamp
0  US.SPY260612C742000  SPY 260612 742.00C        CALL          1816          N/A                 105328.0                     N/A  730160  91928623.0           7449                  432042.0  146.507          0.58       -67.688      0.580       0.56          28       0.60           1  0.43674  0.27447 -455.46028  0.00385  0.0   2026-06-12       1.781237e+09
1  US.SPY260612C745000  SPY 260612 745.00C        CALL          5416          N/A                   5416.0                     N/A  617981  44479304.0          17013                   17013.0   87.067          0.01       -98.958      0.015       0.01         708       0.02         500  0.02438  0.03501  -18.52310  0.00107  0.0   2026-06-12       1.781237e+09
2  US.SPY260612C743000  SPY 260612 743.00C        CALL          5438          N/A                  48942.0                     N/A  606769  64419534.0           7426                   66834.0   59.082          0.09       -93.898      0.095       0.09         208       0.10         118  0.13412  0.19487  -50.92453  0.00405  0.0   2026-06-12       1.781237e+09
3  US.SPY260612P740000  SPY 260612 740.00P         PUT          1223          N/A                   1223.0                     N/A  566915  69291991.0          15291                   15291.0   53.083          0.01       -99.790      0.015       0.01         447       0.02         407 -0.03761  0.08224  -16.47701  0.00153  0.0   2026-06-12       1.781237e+09
4  US.SPY260612C741000  SPY 260612 741.00C        CALL          2924          N/A                 423980.0                     N/A  506505  88981079.0           6229                  903205.0  224.448          1.45       -33.179      1.520       1.46          12       1.58          23  0.63754  0.17055 -662.49947  0.00367  0.0   2026-06-12       1.781237e+09
all_count: 1955829
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the option contract rank interface (for paginated interfaces, only the first call counts)
:::

---

# Option Unusual Activity

`get_option_event(option_market, count=None, page=None, filter_list=None, sort=None)`

* **Description**

    Get option unusual activity list, returns records of large trades, sweeps, and other unusual option activities, with multi-dimensional filtering and sorting by underlying, contract attributes, trade info, Greeks, etc.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    option_market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, US_INDEX=US index options, HK_SECURITY=HK equity options, HK_INDEX=HK index options)
    count|int|Page size  (Range [1,300])
    page|str|Pagination marker  (Pass empty string for the first request, pass the previously returned next_page for subsequent pages)
    filter_list|list[EventFilter]|Filter conditions list  (Multiple conditions are combined with AND logic. Supports filtering by underlying (OWNER_LIST), industry sector, option type (CALL/PUT), trade direction, volume, turnover, IV, Delta, etc.)
    sort|EventSort|Sort order  (Default sorted by time in descending order)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns unusual activity data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * data dictionary contains:

        Field|Type|Description
        :-|:-|:-
        event_list|pandas.DataFrame|Unusual activity list
        next_page|str|Next page marker  (Empty string means no more pages)
        all_count|int|Total count
        update_timestamp|float|Data update timestamp

    * event_list DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        option_code|str|Option contract code
        owner_code|str|Underlying stock code
        symbol|str|Underlying display code (e.g., TSLA)
        fill_time|str|Fill time
        fill_timestamp|float|Fill timestamp (Unix seconds)
        ticker_type|str|Trade direction  (BUY/SELL/NEUTRAL)
        price|float|Fill price
        volume|int|Volume (contracts)
        turnover|float|Turnover
        option_type|str|Option type  (CALL/PUT)
        strike_price|float|Strike price
        strike_time|str|Expiration date
        strike_timestamp|float|Expiration timestamp (Unix seconds)
        dte|int|Days to expiration
        underlying_price|float|Underlying price
        otm|float|Out-of-the-money ratio (percentage)
        bid_price|float|Best bid price
        ask_price|float|Best ask price
        iv|float|Implied volatility (percentage)
        total_volume|int|Option total daily volume
        total_open_interest|int|Option total daily open interest
        vo_ratio|float|Volume/OI ratio (percentage)
        delta|float|Delta
        gamma|float|Gamma
        vega|float|Vega
        theta|float|Theta
        rho|float|Rho
        sentiment|str|Market sentiment  (BEARISH/BULLISH/NEUTRAL)
        order_type_list|list|Order type list  (NORMAL/SWEEP/CROSS/FLOOR)
        strategy_type|str|Strategy type  (SINGLE_LEG/MULTI_LEG)
        earnings_time|str|Earnings time
        earnings_pub_type|int|Earnings publish type
        corporate_action_list|list|Corporate action list
        industry_plate_list|list|Industry plate list
        concept_plate_list|list|Concept plate list

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_event(OptionMarket.US_SECURITY, count=5)
if ret == RET_OK:
    print(data['event_list'])
    print('all_count:', data['all_count'])
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
           option_code owner_code symbol            fill_time  fill_timestamp ticker_type     price  volume   turnover option_type  strike_price strike_time  strike_timestamp  dte  underlying_price    otm  bid_price  ask_price      iv  total_volume  total_open_interest  vo_ratio     delta     gamma      vega     theta       rho sentiment  order_type_list strategy_type earnings_time earnings_pub_type                                                                corporate_action_list industry_plate_list concept_plate_list
0   US.TLT260618C86000     US.TLT    TLT  2026-06-12 16:14:00    1.781295e+09        SELL  0.280000   10000   280000.0        CALL          86.0  2026-06-18      1.781759e+09    3             85.77  0.268       0.28       0.30   8.240         70108                88849   0.78906  0.424382  0.432194  0.043077 -0.034441  0.005940   BEARISH  [SWEEP, NORMAL]    SINGLE_LEG           N/A               N/A                                                                          N/A                 N/A                N/A
1   US.TLT260618C86000     US.TLT    TLT  2026-06-12 16:13:18    1.781295e+09        SELL  0.280000    7821   218988.0        CALL          86.0  2026-06-18      1.781759e+09    3             85.77  0.268       0.28       0.30   8.240         60104                88849   0.67647  0.424382  0.432194  0.043077 -0.034441  0.005940   BEARISH  [SWEEP, NORMAL]    SINGLE_LEG           N/A               N/A                                                                          N/A                 N/A                N/A
2  US.IWM260618P285000     US.IWM    IWM  2026-06-12 16:07:53    1.781295e+09        SELL  1.320000    3002   396264.0         PUT         285.0  2026-06-18      1.781759e+09    3            292.96  2.717       1.32       1.35  28.323         57418                26731   2.14799 -0.214110  0.027402  0.109475 -0.256980 -0.009801   BULLISH  [SWEEP, NORMAL]    SINGLE_LEG           N/A               N/A  [{'action_type': 7, 'action_time': '2026-06-15', 'action_timestamp': ...}]                 N/A                N/A
3  US.SPY260717P706000     US.SPY    SPY  2026-06-12 16:04:46    1.781295e+09         BUY  4.333523    3872  1677940.0         PUT         706.0  2026-07-17      1.784264e+09   32            741.77  4.822       4.29       4.35  19.000         22269                 8169   2.72603 -0.177726  0.005982  0.596630 -0.150480 -0.113947   BEARISH  [SWEEP, NORMAL]    SINGLE_LEG           N/A               N/A                                                                          N/A                 N/A      [US.LIST2153]
4  US.SPY260717P704000     US.SPY    SPY  2026-06-12 16:04:26    1.781295e+09        SELL  4.060235    6767  2747561.0         PUT         704.0  2026-07-17      1.784264e+09   32            741.77  5.091       4.05       4.10  19.214         17712                 7842   2.25860 -0.167963  0.005705  0.575554 -0.147087 -0.107775   BULLISH         [NORMAL]    SINGLE_LEG           N/A               N/A                                                                          N/A                 N/A      [US.LIST2153]
all_count: 164620
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the option unusual activity interface (for paginated interfaces, only the first call counts)
:::

---

# Get Option Event Alert

`get_option_event_alert(count=200, page=None)`

* **Description**

    Query the list of configured option unusual activity alerts, with pagination support.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    count|int|Page size  (Range [1,500], default 200)
    page|str|Pagination marker  (Pass None for the first request, pass next_page for subsequent pages)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns alert data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * data dictionary contains:

        Field|Type|Description
        :-|:-|:-
        alert_list|pandas.DataFrame|Alert settings list
        next_page|str|Next page marker (empty string means no more pages)
        all_count|int|Total alert count

    * alert_list DataFrame columns:

        Field|Type|Description
        :-|:-|:-
        key|int|Alert unique identifier
        enable|bool|Alert switch
        option_market|str|Market category ([OptionMarket](./quote.md#8307) enum value)
        watchlist_group_name|str|Watchlist group name
        underlying|str|Specified underlying code
        option_type|str|Option type (CALL/PUT)
        side_type_list|list|Trade direction list ([EventTickerType](./quote.md#8511) enum values)
        order_type_list|list|Order type list ([AlertOrderType](./quote.md#385) enum values)
        market_cap_range_min|float|Underlying market cap lower bound
        market_cap_range_max|float|Underlying market cap upper bound
        market_cap_min_inclusive|bool|Whether market cap lower bound is inclusive
        market_cap_max_inclusive|bool|Whether market cap upper bound is inclusive
        expiry_days_range_min|float|Days to expiration lower bound
        expiry_days_range_max|float|Days to expiration upper bound
        expiry_days_min_inclusive|bool|Whether days to expiration lower bound is inclusive
        expiry_days_max_inclusive|bool|Whether days to expiration upper bound is inclusive
        price_range_min|float|Event fill price lower bound
        price_range_max|float|Event fill price upper bound
        price_min_inclusive|bool|Whether fill price lower bound is inclusive
        price_max_inclusive|bool|Whether fill price upper bound is inclusive
        size_range_min|float|Event volume lower bound (contracts)
        size_range_max|float|Event volume upper bound (contracts)
        size_min_inclusive|bool|Whether volume lower bound is inclusive
        size_max_inclusive|bool|Whether volume upper bound is inclusive
        premium_range_min|float|Event turnover lower bound
        premium_range_max|float|Event turnover upper bound
        premium_min_inclusive|bool|Whether turnover lower bound is inclusive
        premium_max_inclusive|bool|Whether turnover upper bound is inclusive
        iv_range_min|float|Implied volatility lower bound (%)
        iv_range_max|float|Implied volatility upper bound (%)
        iv_min_inclusive|bool|Whether IV lower bound is inclusive
        iv_max_inclusive|bool|Whether IV upper bound is inclusive
        earnings_date_begin|str|Earnings date filter start date (yyyy-MM-dd)
        earnings_date_end|str|Earnings date filter end date (yyyy-MM-dd)
        note|str|Note

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_event_alert()
if ret == RET_OK:
    print(data['alert_list'])
    print('all_count:', data['all_count'])
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
     key  enable option_market watchlist_group_name underlying option_type side_type_list order_type_list  market_cap_range_min  market_cap_range_max market_cap_min_inclusive market_cap_max_inclusive  expiry_days_range_min  expiry_days_range_max expiry_days_min_inclusive expiry_days_max_inclusive  price_range_min  price_range_max price_min_inclusive price_max_inclusive  size_range_min  size_range_max size_min_inclusive size_max_inclusive  premium_range_min  premium_range_max premium_min_inclusive premium_max_inclusive  iv_range_min  iv_range_max iv_min_inclusive iv_max_inclusive earnings_date_begin earnings_date_end  note
0  14743   False   US_SECURITY                  N/A        N/A        CALL            N/A         [SWEEP]                   N/A                   N/A                     N/A                      N/A                    N/A                    N/A                      N/A                       N/A              N/A              N/A                N/A                N/A           100.0             N/A              True               N/A                N/A                N/A                  N/A                   N/A           N/A           N/A             N/A             N/A                 N/A               N/A  test
all_count: 1
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the get option event alert interface (for paginated interfaces, only the first call counts)
:::

---

# Set Option Event Alert

`set_option_event_alert(op, alert_list=None)`

* **Description**

    Add, modify, delete, or enable/disable option unusual activity alerts.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    op|[AlertOpType](./quote.md#1999)|Operation type  (ADD=Add, DELETE=Delete, MODIFY=Modify, ENABLE=Enable, DISABLE=Disable, DELETE_ALL=Delete all)
    alert_list|OptionEventAlertItem or list[OptionEventAlertItem]|Alert item(s)  (Do not pass key when adding, key is required when modifying/deleting)

    * OptionEventAlertItem fields:

        Field|Type|Description
        :-|:-|:-
        key|int|Alert unique identifier (required for modify/delete/enable/disable)
        enable|bool|Alert switch
        option_market|[OptionMarket](./quote.md#8307)|Option market to monitor (one of three)
        watchlist_group_name|str|Watchlist group name (one of three)
        underlying|str|Specified underlying code, e.g. `'US.AAPL'` (one of three)
        option_type|OptionType|Option type (CALL/PUT)
        side_type_list|list[[EventTickerType](./quote.md#8511)]|Trade direction list
        order_type_list|list[[AlertOrderType](./quote.md#385)]|Order type list
        market_cap_range_min|float|Underlying market cap lower bound
        market_cap_range_max|float|Underlying market cap upper bound
        market_cap_min_inclusive|bool|Whether market cap lower bound is inclusive (default True)
        market_cap_max_inclusive|bool|Whether market cap upper bound is inclusive (default True)
        expiry_days_range_min|float|Days to expiration lower bound
        expiry_days_range_max|float|Days to expiration upper bound
        expiry_days_min_inclusive|bool|Whether days to expiration lower bound is inclusive (default True)
        expiry_days_max_inclusive|bool|Whether days to expiration upper bound is inclusive (default True)
        price_range_min|float|Event fill price lower bound
        price_range_max|float|Event fill price upper bound
        price_min_inclusive|bool|Whether fill price lower bound is inclusive (default True)
        price_max_inclusive|bool|Whether fill price upper bound is inclusive (default True)
        size_range_min|float|Event volume lower bound (contracts)
        size_range_max|float|Event volume upper bound (contracts)
        size_min_inclusive|bool|Whether volume lower bound is inclusive (default True)
        size_max_inclusive|bool|Whether volume upper bound is inclusive (default True)
        premium_range_min|float|Event turnover lower bound
        premium_range_max|float|Event turnover upper bound
        premium_min_inclusive|bool|Whether turnover lower bound is inclusive (default True)
        premium_max_inclusive|bool|Whether turnover upper bound is inclusive (default True)
        iv_range_min|float|Implied volatility lower bound (%)
        iv_range_max|float|Implied volatility upper bound (%)
        iv_min_inclusive|bool|Whether IV lower bound is inclusive (default True)
        iv_max_inclusive|bool|Whether IV upper bound is inclusive (default True)
        earnings_date_begin|str|Earnings date filter start date (yyyy-MM-dd)
        earnings_date_end|str|Earnings date filter end date (yyyy-MM-dd)
        note|str|Note (max 20 characters)

    > **Monitoring scope**: `option_market`, `watchlist_group_name`, and `underlying` are mutually exclusive. One must be set when adding a new alert.

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>str</td>
            <td>When ret == RET_OK, returns empty string</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Add an alert: monitor US stock option market CALL sweeps, volume > 100 (exclusive)
item = OptionEventAlertItem(
    option_market=OptionMarket.US_SECURITY,
    option_type=OptionType.CALL,
    order_type_list=[AlertOrderType.SWEEP],
    size_range_min=100,
    size_min_inclusive=False,
    note='test'
)
ret, data = quote_ctx.set_option_event_alert(AlertOpType.ADD, item)
if ret == RET_OK:
    print('Added successfully')
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Added successfully
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds for the set option event alert interface
:::

---

# Option Event Push

`class OptionEventHandlerBase(RspHandlerBase)`

* **Description**

    Receive option event push notifications. When a configured event alert is triggered, the server will actively push the event information. You need to first set alert conditions via `set_option_event_alert` and register a callback via handler. Users inherit `OptionEventHandlerBase` and override `on_recv_rsp` to receive push notifications.

* **Parameters**

    on_recv_rsp callback returns (ret_code, content), where content is a dict:

    Parameter|Type|Description
    :-|:-|:-
    owner_code|str|Underlying code (e.g. 'US.TSLA')
    option_code|str|Option contract code (e.g. 'US.TSLA250620C250')
    message|str|Push message text

* **Example**

```python
from moomoo import *

class OptionEventHandler(OptionEventHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, content = super(OptionEventHandler, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("OptionEvent error:", content)
            return RET_ERROR, content

        print("Received option event push:")
        print("  Underlying:", content['owner_code'])
        print("  Option:", content['option_code'])
        print("  Message:", content['message'])
        return RET_OK, content

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Register option event push handler
quote_ctx.set_handler(OptionEventHandler())

# Must first set alert conditions via set_option_event_alert before pushes are triggered
item = OptionEventAlertItem(
    option_market=OptionMarket.US_SECURITY,
    option_type=OptionType.CALL,
    order_type_list=[AlertOrderType.SWEEP],
    size_range_min=100,
)
ret, data = quote_ctx.set_option_event_alert(AlertOpType.ADD, item)
if ret == RET_OK:
    print('Alert set successfully, waiting for push...')
else:
    print('Failed to set alert:', data)

import time
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    pass

quote_ctx.close()
```

* **Output**

```
Received option event push:
  Underlying: US.TSLA
  Option: US.TSLA250620C250
  Message: TSLA $250 Call 06/20 Large sweep 500 contracts at $12.50
```

---

# Zero DTE Option Screener

`get_option_zero_dte_screener(market, sort_type=None, is_asc=None, count=None, page=None, filter_list=None)`

* **Description**

    Get the zero DTE option underlying screener list, returning underlying stock information for options expiring on the current day (0DTE), including volatility, option volume, open interest, and option chain information.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, US_INDEX=US index options (US market only))
    sort_type|[ZeroDteSortType](./quote.md#3004)|Sort type  (VOLUME=option volume, IV=implied volatility, CHANGE_RATIO=price change, OPEN_INTEREST=open interest, MARKET_CAP=market cap)
    is_asc|bool|Ascending order  (Default False (descending))
    count|int|Items per page  (Range [1,500], default 50)
    page|str|Pagination cursor  (Leave empty or omit for first call, pass next_page for subsequent pages)
    filter_list|list[ZeroDteFilter]|Filter conditions list  (Multiple conditions use AND logic. Supports OWNER_LIST, HAS_EARNINGS_THIS_WEEK, VOLUME, OPEN_INTEREST, IV, HV, IV_RANK, IV_PERCENTILE, PRICE, CHANGE_RATIO)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns a dict containing item_list (DataFrame), next_page (str/None), update_timestamp (float)</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        owner|str|Underlying stock code
        name|str|Underlying name
        price|float|Underlying current price
        change_ratio|float|Price change (percentage)
        market_cap|float|Market capitalization
        iv|float|Implied volatility (percentage)
        iv_rank|float|IV rank (percentage)
        iv_percentile|float|IV percentile (percentage)
        hv|float|Historical volatility (percentage)
        volume|int|Option volume
        open_interest|int|Option open interest
        last_trading_time|int|Last trading timestamp (Unix seconds)
        earnings_timestamp|int|Earnings date timestamp (seconds)
        earnings_time|str|Earnings time string
        earnings_pub_type|str|Earnings release type (BEFORE/AFTER)
        chain_info|dict|Option chain information  (Used for get_option_zero_dte_contract call)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_zero_dte_screener(
    market=OptionMarket.US_SECURITY,
    sort_type=ZeroDteSortType.VOLUME,
    is_asc=False,
    count=5
)
if ret == RET_OK:
    print(data['item_list'])
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
     owner                        name   price  change_ratio    market_cap      iv  iv_rank  iv_percentile      hv    volume  open_interest  last_trading_time earnings_timestamp earnings_time earnings_pub_type                                                                                                                chain_info
0   US.SPY               标普500ETF-SPDR  741.75         0.540  7.830717e+11  17.675   27.143         61.111  15.031  14228830       19909256         1781554500                N/A           N/A               N/A    {'strike_date_timestamp': 1781499600, 'product_code': 'SPY', 'multiplier': 100.0, ...}
1   US.QQQ  纳指100ETF-Invesco QQQ Trust  721.34         0.588  4.805349e+11  27.652   62.918         91.269  26.196   8239190       12964422         1781554500                N/A           N/A               N/A    {'strike_date_timestamp': 1781499600, 'product_code': 'QQQ', 'multiplier': 100.0, ...}
2  US.TSLA                         特斯拉  406.43         1.823  1.526439e+12  55.053   39.265         64.285  49.359   3623504        7088459         1781553600                N/A           N/A               N/A  {'strike_date_timestamp': 1781499600, 'product_code': 'TSLA', 'multiplier': 100.0, ...}
3  US.NVDA                         英伟达  205.19         0.156  4.965598e+12  41.975   27.062         42.460  45.921   3157331       16744961         1781553600                N/A           N/A               N/A  {'strike_date_timestamp': 1781499600, 'product_code': 'NVDA', 'multiplier': 100.0, ...}
4   US.IWM           罗素2000ETF-iShares  292.95         0.874  8.143528e+10  24.857   33.930         64.285  24.802   2840729       11791964         1781554500                N/A           N/A               N/A    {'strike_date_timestamp': 1781499600, 'product_code': 'IWM', 'multiplier': 100.0, ...}
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds (for paginated interfaces, only the first call counts)
:::

---

# Zero DTE Option Contracts

`get_option_zero_dte_contract(owner, strike_date_timestamp, chain_info, sort_type=None, is_asc=None, filter_list=None)`

* **Description**

    Get zero DTE option contract list, returning 0DTE option contract details for a specified underlying on a specified strike date, including Greeks, break-even points, and profit probabilities.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    owner|str|Underlying stock code  (e.g. 'US.AAPL', US stocks only)
    strike_date_timestamp|int|Strike date timestamp (Unix seconds)
    chain_info|dict|Option chain information  (From chain_info returned by get_option_zero_dte_screener)
    sort_type|[ZeroDteContractSortType](./quote.md#5977)|Sort type  (VOLUME=volume, OPEN_INTEREST=open interest, IV=implied volatility, DELTA=Delta)
    is_asc|bool|Ascending order  (Default False (descending))
    filter_list|list[ZeroDteContractFilter]|Filter conditions list  (Multiple conditions use AND logic. Supports OPTION_TYPE, VOLUME, OPEN_INTEREST, IV, DELTA, GAMMA, THETA, VEGA, RHO, PRICE, CHANGE_RATIO, BREAK_EVEN_POINT, TO_BEP, BUY_PROFIT_PROBABILITY, SELL_PROFIT_PROBABILITY)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns contract list</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        option|str|Option contract code
        name|str|Contract name
        option_type|str|Option type (CALL/PUT)
        option_price|float|Option price
        change_ratio|float|Price change (percentage)
        volume|int|Volume
        open_interest|int|Open interest
        iv|float|Implied volatility (percentage)
        delta|float|Delta
        gamma|float|Gamma
        vega|float|Vega
        theta|float|Theta
        rho|float|Rho
        buy_break_even_point|float|Buy break-even point
        buy_to_bep|float|Price change needed to reach break-even (percentage)
        buy_profit_probability|float|Buy profit probability (percentage)
        sell_profit_probability|float|Sell profit probability (percentage)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# 第一步：获取末日期权标的列表
ret, screener_data = quote_ctx.get_option_zero_dte_screener(
    market=OptionMarket.US_SECURITY,
    sort_type=ZeroDteSortType.VOLUME,
    is_asc=False,
    count=1
)
if ret != RET_OK:
    print('error:', screener_data)
    quote_ctx.close()
    exit()

# 第二步：取第一个标的的 chain_info，查询其合约列表
df = screener_data['item_list']
owner = df.iloc[0]['owner']
chain_info = df.iloc[0]['chain_info']
strike_date_timestamp = chain_info['strike_date_timestamp']

ret, data = quote_ctx.get_option_zero_dte_contract(
    owner=owner,
    strike_date_timestamp=strike_date_timestamp,
    chain_info=chain_info,
    sort_type=ZeroDteContractSortType.VOLUME,
    is_asc=False
)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
              option             name option_type  option_price  change_ratio  volume  open_interest    iv   delta   gamma    vega   theta     rho  buy_break_even_point  buy_to_bep  buy_profit_probability  sell_profit_probability
0  US.SPY260612C742000  SPY 260612 C742        CALL          0.58       -67.688  730160           7449  146.5  0.4367  0.2745  0.0039  -455.46  0.000                742.58        0.11                   43.5                    56.5
1  US.SPY260612C745000  SPY 260612 C745        CALL          0.01       -98.958  617981          17013   87.1  0.0244  0.0350  0.0011   -18.52  0.000                745.01        0.44                    2.4                    97.6
...
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds
:::

---

# Option Earnings Screener

`get_option_earnings_screener(market, sort_type=None, is_asc=None, count=None, page=None, filter_list=None)`

* **Description**

    Get the list of option underlyings with upcoming earnings releases, returning volatility data, historical earnings IV crush, stock price movement, and market expectations to help users make option trading decisions during earnings season.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, HK_SECURITY=HK equity options)
    sort_type|[EarningsSortType](./quote.md#601)|Sort type  (EARNINGS_DATE=earnings date (default), VOLUME=option volume, IV=implied volatility, MARKET_CAP=market cap, CHANGE_RATIO=price change, PRICE=latest price, IV_RANK=IV rank, IV_PERCENTILE=IV percentile, HV=historical volatility, OPEN_INTEREST=open interest, LAST_REPORT_IV_CRUSH=last IV crush, HISTORY_REPORT_IV_CRUSH=historical IV crush, LAST_REPORT_CHG_RATIO=last earnings price change, HISTORY_REPORT_CHG_RATIO=historical earnings price change, ESTIMATE_EPS_YOY=estimated EPS YoY, ESTIMATE_REVENUE_YOY=estimated revenue YoY, EXPECTED_MOVE_RATIO=expected move)
    is_asc|bool|Ascending order  (Default True)
    count|int|Items per page  (Range [1,500], default 50)
    page|str|Pagination cursor  (Leave empty or omit for first call, pass next_page for subsequent pages)
    filter_list|list[EarningsFilter]|Filter conditions list  (Multiple conditions use AND logic)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns a dict containing item_list (DataFrame), next_page (str), update_timestamp (float), all_count (int)</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        owner|str|Underlying stock code
        name|str|Underlying name
        price|float|Underlying current price
        change_ratio|float|Price change ratio (decimal)
        market_cap|float|Market capitalization
        iv|float|Implied volatility (percentage)
        iv_rank|float|IV rank (percentage)
        iv_percentile|float|IV percentile (percentage)
        hv|float|Historical volatility (percentage)
        volume|int|Option volume
        open_interest|int|Option open interest
        earnings_timestamp|float|Earnings date timestamp (Unix seconds)
        earnings_time|str|Earnings date string (yyyy-MM-dd)
        earnings_pub_type|str|Earnings release type (BEFORE=pre-market/AFTER=post-market)
        earnings_quarter|str|Earnings quarter (e.g. '2025Q1')
        last_report_iv_crush|float|Last earnings IV crush (percentage)
        history_report_iv_crush|float|Historical average earnings IV crush (percentage)
        last_report_chg_ratio|float|Last post-earnings stock price change (decimal)
        history_report_chg_ratio|float|Historical average post-earnings stock price change (decimal)
        estimate_eps_yoy|float|Estimated EPS year-over-year growth (percentage)
        estimate_revenue_yoy|float|Estimated revenue year-over-year growth (percentage)
        expected_move_ratio|float|Option implied expected move (percentage)

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_earnings_screener(
    market=OptionMarket.US_SECURITY,
    count=5
)
if ret == RET_OK:
    print(data['item_list'])
    print('all_count:', data['all_count'])
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
     owner                           name  price  change_ratio    market_cap       iv  iv_rank  iv_percentile      hv  volume  open_interest  earnings_timestamp earnings_time earnings_pub_type earnings_quarter  last_report_iv_crush  history_report_iv_crush  last_report_chg_ratio  history_report_chg_ratio  estimate_eps_yoy  estimate_revenue_yoy  expected_move_ratio
0   US.CGC                  Canopy Growth   1.00        -0.990  4.220190e+08  204.207   36.550         88.492  39.545    8131         328382        1.781496e+09    2026-06-15            BEFORE           2026Q4               -21.308                   11.782                  1.851                    12.761            94.055                14.340               12.500
1  US.PLAY  Dave & Buster's Entertainment  12.93        -1.896  4.491805e+08  114.030   99.492         99.603  62.390    3052          44247        1.781496e+09    2026-06-15             AFTER           2027Q1                22.640                   26.059                 16.066                    15.892            -3.758                 1.881               15.409
2  US.DOMO                       Domo Inc   3.02         2.027  1.363547e+08  165.563   72.093         96.825  90.389    1970          29748        1.781496e+09    2026-06-15             AFTER           2027Q1                23.532                   30.013                 13.470                    19.203             9.622                -0.451               30.629
3  US.CMTL                       Comverse   4.83         5.228  1.436158e+08  388.934   81.297         98.412 106.150     218          13434        1.781496e+09    2026-06-15            BEFORE           2026Q3               154.978                   51.309                -24.536                    16.278           -10.204               -13.078               23.809
4  US.RFIL                  RF Industries  18.75         0.969  2.027675e+08  100.939   11.123         54.365  83.526     215           2044        1.781496e+09    2026-06-15             AFTER           2026Q2               -14.722                    6.537                 12.318                    12.013           200.000                 3.997               15.466
all_count: 292
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds (for paginated interfaces, only the first call counts)
:::

---

# Option Seller Screener

`get_option_seller_screener(market, seller_type, sort_type=None, is_asc=None, filter_list=None)`

* **Description**

    Get the option seller screener list, returning option contracts suitable for seller strategies (Cash Secured Put / Covered Call), including return rates, exercise probabilities, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[OptionMarket](./quote.md#8307)|Option market type  (US_SECURITY=US equity options, HK_SECURITY=HK equity options)
    seller_type|[SellerType](./quote.md#9968)|Seller strategy type  (COVERED_CALL=covered call, CASH_SECURED_PUT=cash secured put (HK market only supports CASH_SECURED_PUT))
    sort_type|[SellerSortType](./quote.md#377)|Sort type  (ANNUALIZED_RETURN=annualized return, INTERVAL_RETURN=interval return, ITM_PROBABILITY=exercise probability, PREMIUM=premium)
    is_asc|bool|Ascending order  (Default False (descending))
    filter_list|list[SellerFilter]|Filter conditions list  (Multiple conditions use AND logic)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>Interface call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pandas.DataFrame</td>
            <td>When ret == RET_OK, returns screener results</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Return DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        option|str|Option contract code
        name|str|Option name
        option_type|str|Option direction  (CALL, PUT)
        strike_price|float|Strike price
        strike_time|str|Expiration date time string
        strike_timestamp|float|Expiration date timestamp (Unix seconds)
        left_days|int|Days to expiry
        option_price|float|Option price
        stock_price|float|Underlying stock price
        premium|float|Premium
        otm_degree|float|Out-of-the-money degree (%)
        iv|float|Implied volatility (%)
        interval_return|float|Interval return (%)
        annualized_return|float|Annualized return (%)
        itm_probability|float|Exercise probability (%)
        striked_interval_return|float|Assigned interval return (%)  (Covered Call only)
        striked_annualized_return|float|Assigned annualized return (%)  (Covered Call only)
        owner|str|Underlying stock code

* **Example**

```python
from moomoo import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_option_seller_screener(
    market=OptionMarket.US_SECURITY,
    seller_type=SellerType.COVERED_CALL,
    sort_type=SellerSortType.ANNUALIZED_RETURN,
    is_asc=False
)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
                 option                 name option_type  strike_price strike_time  strike_timestamp  left_days  option_price  stock_price  premium  otm_degree       iv  interval_return  annualized_return  itm_probability  striked_interval_return  striked_annualized_return    owner
0  US.SOXL260618C235000  SOXL 260618 235.00C        CALL         235.0  2026-06-18      1.781755e+09          3        21.850       234.68   2185.0       0.136  234.988           10.266           1074.855           45.724                   10.416                   1090.597  US.SOXL
1  US.SOXL260618C237500  SOXL 260618 237.50C        CALL         237.5  2026-06-18      1.781755e+09          3        20.675       234.68   2067.5       1.201  234.423            9.660           1011.470           43.682                   10.978                   1149.431  US.SOXL
2  US.SOXL260618C240000  SOXL 260618 240.00C        CALL         240.0  2026-06-18      1.781755e+09          3        19.250       234.68   1925.0       2.266  230.652            8.935            935.526           41.678                   11.405                   1194.071  US.SOXL
3    US.WDS260618C25000    WDS 260618 25.00C        CALL          25.0  2026-06-18      1.781755e+09          3         1.875        23.07    187.5       8.365  292.148            8.846            928.963           11.794                   17.952                   1885.177   US.WDS
4  US.SOXL260618C242500  SOXL 260618 242.50C        CALL         242.5  2026-06-18      1.781755e+09          3        18.350       234.68   1835.0       3.332  232.108            8.482            888.077           39.715                   12.097                   1266.538  US.SOXL
...
```

:::tip Rate Limit
* Maximum 60 requests per 30 seconds
:::

---

# Get Filtered Warrant

`get_warrant(stock_owner='', req=None)`

* **Description**

    Get Filtered Warrant (only warrants, CBBCs and Inline Warrants of HK market are surpported)

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    stock_owner|str|Code of the underlying stock.
    req|*WarrantRequest*|Filter parameter combination.
    * *WarrantRequest*'s details as follows: 
        Field|Type|Description
        :-|:-|:-
        begin|int|Data start point
        num|int|The number of requested data.  (The maximum is 200.)
        sort_field|[SortField](./quote.md#5823)|According to which field to sort.
        ascend|bool|The sort direction.  (True: ascending order. False: descending order.)
        type_list|list|Warrant Type Filter List.  (Data type of elements in the list is [WrtType](./quote.md#2421).)
        issuer_list|list|Issuer filter list.  (Data type of elements in the list is [Issuer](./quote.md#5122).)
        maturity_time_min|str|The start time of the maturity date filter range.
        maturity_time_max|str|The end time of the maturity date filter range.
        ipo_period|[IpoPeriod](./quote.md#2961)|Listing period.
        price_type|[PriceType](./quote.md#9794)|In/out of the money.  (The Inline Warrant is not currently supported.)
        status|[WarrantStatus](./quote.md#5892)|Warrant Status.
        cur_price_min|float|The filter lower limit (closed interval) of the latest price.  (If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        cur_price_max|float|The filter upper limit (closed interval) of the latest price.  (If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        strike_price_min|float|The lower filter limit (closed interval) of the strike price.  (If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        strike_price_max|float|The upper filter limit (closed interval) of the strike price.  (If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        street_min|float|The lower limit (closed interval) of Outstanding percentage.  (If not passed, the lower limit is -∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)
        street_max|float|The upper limit (closed interval) of Outstanding percentage.  (If not passed, the upper limit is +∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)
        conversion_min|float|The lower filter limit (closed interval) of the conversion ratio.  (If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        conversion_max|float|The upper filter limit (closed interval) of the conversion ratio.  (If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        vol_min|int|The lower filter limit (closed interval) of the volume.  (If not passed, the lower limit is -∞.)
        vol_max|int|The upper filter limit (closed interval) of the volume.  (If not passed, the upper limit is +∞.)
        premium_min|float|The lower filter limit (closed interval) of premium value.  (If not passed, the lower limit is -∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)
        premium_max|float|The upper filter limit (closed interval) of premium value.  (If not passed, the upper limit is +∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)
        leverage_ratio_min|float|The lower filter limit (closed interval) of the leverage ratio.  (If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        leverage_ratio_max|float|The upper filter limit (closed interval) of the leverage ratio.  (If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        delta_min|float|The lower filter limit (closed interval) of the hedge value Delta.  (If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        delta_max|float|The upper filter limit (closed interval) of the hedge value Delta.  (If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        implied_min|float|The lower filter limit (closed interval) of the implied volatility.  (Only calls and puts support this filtering field. If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        implied_max|float|The upper filter limit (closed interval) of the implied volatility.  (Only calls and puts support this filtering field. If not passed, the upper limit is +∞(3 decimal place accuracy, the excess part is discarded.)
        recovery_price_min|float|The lower filter limit (closed interval) of the recovery price.  (Only CBBCs support this field to filter. If not passed, the lower limit is -∞.3 decimal place accuracy, the excess part is discarded.)
        recovery_price_max|float|The upper filter limit (closed interval) of the recovery price.  (Only CBBCs support this field to filter. If not passed, the upper limit is +∞.3 decimal place accuracy, the excess part is discarded.)
        price_recovery_ratio_min|float|The lower filter limit (closed interval) of the price recovery ratio.  (Only CBBCs support this field. If not passed, the lower limit is -∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)
        price_recovery_ratio_max|float|The upper filter limit (closed interval) of the price recovery ratio.   (Only CBBCs support this field. If not passed, the upper limit is +∞.This field is in percentage form, so 20 is equivalent to 20%.3 decimal place accuracy, the excess part is discarded.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, warrant data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Warrant data format as follows: 
        Field|Type|Description
        :-|:-|:-
        warrant_data_list|pd.DataFrame|Warrant data after filtering.
        last_page|bool|Weather is the last page.  (True: the last page. False: not the last page.)
        all_count|int|The total number of warrants in the filtered result.

        - Warrant_data_list's detail as follows: 
            Field|Type|Description
            :-|:-|:-
            stock|str|Warrant code.
            stock_owner|str|Underlying stock.
            type|[WrtType](./quote.md#2421)|Warrant type.
            issuer|[Issuer](./quote.md#5122)|Issuer.
            maturity_time|str|Maturity date.  (Format: yyyy-MM-dd)
            list_time|str|Listing time.  (Format: yyyy-MM-dd)
            last_trade_time|str|Last trading day.  (Format: yyyy-MM-dd)
            recovery_price|float|Recovery price.  (Only CBBCs support this field.)
            conversion_ratio|float|Conversion ratio.
            lot_size|int|Quantity per lot.
            strike_price|float|Strike price.
            last_close_price|float|Yesterday's close.
            name|str|Name.
            cur_price|float|Current price.
            price_change_val|float|Price change.
            status|[WarrantStatus](./quote.md#5892)|Warrant status.
            bid_price|float|Bid price.
            ask_price|float|Ask price.
            bid_vol|int|Bid volume.
            ask_vol|int|Ask volume.
            volume|unsigned int|Volume.
            turnover|float|Turnover.
            score|float|Comprehensive score.
            premium|float|Premium.  (This field is in percentage form, so 20 is equivalent to 20%.)
            break_even_point|float|Breakeven point.
            leverage|float|Leverage ratio.
            ipop|float|In/out of the money.  (This field is in percentage form, so 20 is equivalent to 20%.)
            price_recovery_ratio|float|Price recovery ratio.  (Only CBBC supports this field.This field is in percentage form, so 20 is equivalent to 20%.)
            conversion_price|float|Conversion price.
            street_rate|float|Outstanding percentage.  (This field is in percentage form, so 20 is equivalent to 20%.)
            street_vol|int|Outstanding quantity.
            amplitude|float|Amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
            issue_size|int|Issue size.
            high_price|float|High.
            low_price|float|Low.
            implied_volatility|float|Implied volatility.  (Only calls and puts support this field.)
            delta|float|Hedging value.  (Only calls and puts support this field.)
            effective_leverage|float|Effective leverage.
            upper_strike_price|float|Upper bound price.  (Only Inline Warrants support this field.)
            lower_strike_price|float|Lower bound price.  (Only Inline Warrants support this field.)
            inline_price_status|[PriceType](./quote.md#9794)|In/out of bounds.  (Only Inline Warrants support this field.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

req = WarrantRequest()
req.sort_field = SortField.TURNOVER
req.type_list = WrtType.CALL
req.cur_price_min = 0.1
req.cur_price_max = 0.2
ret, ls = quote_ctx.get_warrant("HK.00700", req)
if ret == RET_OK: # First judge whether the interface return is normal, and then fetch the data
    warrant_data_list, last_page, all_count = ls
    print(len(warrant_data_list), all_count, warrant_data_list)
    print(warrant_data_list['stock'][0]) # Take the first warrant code
    print(warrant_data_list['stock'].values.tolist()) # Convert to list
else:
    print('error: ', ls)
    
req = WarrantRequest()
req.sort_field = SortField.TURNOVER
req.issuer_list = ['UB','CS','BI']
ret, ls = quote_ctx.get_warrant(Market.HK, req)
if ret == RET_OK: 
    warrant_data_list, last_page, all_count = ls
    print(len(warrant_data_list), all_count, warrant_data_list)
else:
    print('error: ', ls)

quote_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
2 2 
    stock        name stock_owner  type issuer maturity_time   list_time last_trade_time  recovery_price  conversion_ratio  lot_size  strike_price  last_close_price  cur_price  price_change_val  change_rate  status  bid_price  ask_price   bid_vol  ask_vol    volume   turnover   score  premium  break_even_point  leverage    ipop  price_recovery_ratio  conversion_price  street_rate  street_vol  amplitude  issue_size  high_price  low_price  implied_volatility  delta  effective_leverage  list_timestamp  last_trade_timestamp  maturity_timestamp  upper_strike_price  lower_strike_price  inline_price_status
0   HK.20306  MBTENCT@EC2012A    HK.00700  CALL     MB    2020-12-01  2019-06-27      2020-11-25             NaN              50.0      5000        588.88             0.188      0.188             0.000     0.000000  NORMAL      0.000      0.188         0     10000           0          0.0   0.196    1.921            598.28    62.446  -0.319                   NaN              9.40        4.400     1584000      0.000    36000000       0.000      0.000              32.487  0.473              29.536    1.561565e+09          1.606234e+09        1.606752e+09                 NaN                 NaN                  NaN
1   HK.16545  SGTENCT@EC2102B    HK.00700  CALL     SG    2021-02-26  2020-07-14      2021-02-22             NaN             100.0     10000        700.00             0.147      0.143            -0.004    -2.721088  NORMAL      0.141      0.143  28000000  28000000           0          0.0  82.011   21.686            714.30    41.048 -16.142                   NaN             14.30        1.420     2130000      0.000   150000000       0.000      0.000              40.657  0.225               9.235    1.594656e+09          1.613923e+09        1.614269e+09                 NaN                 NaN                  NaN
HK.20306
['HK.20306', 'HK.16545']

200 358
    stock        name stock_owner    type issuer maturity_time   list_time last_trade_time  recovery_price  conversion_ratio  lot_size  strike_price  last_close_price  cur_price  price_change_val  change_rate      status  bid_price  ask_price   bid_vol   ask_vol  volume  turnover   score  premium  break_even_point  leverage     ipop  price_recovery_ratio  conversion_price  street_rate  street_vol  amplitude  issue_size  high_price  low_price  implied_volatility  delta  effective_leverage  list_timestamp  last_trade_timestamp  maturity_timestamp  upper_strike_price  lower_strike_price inline_price_status
0    HK.19839   PINGANRUIYINLINGYIGOUAC    HK.02318    CALL     UB    2020-12-31  2017-12-11      2020-12-24             NaN             100.0     50000         83.88             0.057      0.046            -0.011   -19.298246      NORMAL      0.043      0.046  30000000  30000000       0       0.0  39.585    1.642            88.480    18.923    3.779                   NaN             4.600         1.25     6250000        0.0   500000000         0.0        0.0              25.129  0.692              13.094    1.512922e+09          1.608739e+09        1.609344e+09                 NaN                 NaN                 NaN
1    HK.20084   PINGANZHONGYINLINGYIGOUAC    HK.02318    CALL     BI    2020-12-31  2017-12-19      2020-12-24             NaN             100.0     50000         83.88             0.059      0.050            -0.009   -15.254237      NORMAL      0.044      0.050  10000000  10000000       0       0.0   0.064    2.102            88.880    17.410    3.779                   NaN             5.000         0.07      350000        0.0   500000000         0.0        0.0              29.510  0.668              11.629    1.513613e+09          1.608739e+09        1.609344e+09                 NaN                 NaN                 NaN
......
198  HK.56886   UB#HSI  RC2301F   HK.800000    BULL     UB    2023-01-30  2020-03-24      2023-01-27         21200.0           20000.0     10000      21100.00             0.230      0.232             0.002     0.869565      NORMAL      0.232      0.233  30000000  30000000       0       0.0  46.619   -2.916         25740.000     5.714   25.655             25.062689          4640.000         0.01       40000        0.0   400000000         0.0        0.0                 NaN    NaN               5.714    1.584979e+09          1.674749e+09        1.675008e+09                 NaN                 NaN                 NaN
199  HK.56895   UB#XIAMIRC2012D    HK.01810    BULL     UB    2020-12-30  2020-03-24      2020-12-29             8.0              10.0      2000          7.60             2.010      1.930            -0.080    -3.980100      NORMAL      1.910      1.930   6000000   6000000       0       0.0   0.040    1.127            26.900     1.378  250.000            232.500000            19.300         0.10       60000        0.0    60000000         0.0        0.0                 NaN    NaN               1.378    1.584979e+09          1.609171e+09        1.609258e+09                 NaN                 NaN                 NaN

```

:::tip Interface Limitations
* Hong Kong stock BMP permission does not support calling this API
* A maximum of 60 requests per 30 seconds
* The maximum number of data per request is 200
:::

---

# Warrant Screening V2

`get_warrant_screen(request)`

* **Description**

    Warrant screening V2. Compared with the legacy [get_warrant](./get-warrant.md), this API returns 45 columns of warrant attributes, supports HK / Singapore / Malaysia markets, and supports a count-only mode (only_count). All numeric fields accept raw values; OpenD performs magnification conversion internally.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    request|WarrantScreenRequest|Warrant screening request object; warrant_market must be passed at construction

    * WarrantScreenRequest fields:

        Field|Type|Description
        :-|:-|:-
        warrant_market|[WarrantMarket](./quote.md#1724)|Market  (HK=1, SG=4, MY=15)
        is_delay|bool|Whether to use delayed market data  (Defaults to False)
        only_count|bool|Whether to return only the total count (no detailed records)  (Defaults to False; when True only all_count is filled and DataFrame is empty)
        page_from|int|Pagination start position  (Defaults to 0)
        page_count|int|Maximum results per page  (Defaults to 200)

    * Filter builder methods (each call appends one filter condition):

        Method|Description
        :-|:-
        add_interval_filter(field_id, min_val=None, max_val=None, min_included=True, max_included=True)|Interval filter  (field_id comes from [WarrantField](./quote.md#9880); min_val / max_val are passed as raw values (OpenD performs magnification automatically, e.g. current price 5 → 5.0, street ratio 50% → 50.0, effective leverage > 3 → 3.0); both min_val and max_val are optional, and omitting both makes this condition a no-op (equivalent to no filter))
        add_choice_filter(field_id, choices)|Choice filter  (choices may be int enums or string codes; e.g. STOCK_OWNER accepts ["HK.00700"], WARRANT_TYPE accepts [WarrantType.CALL, WarrantType.PUT])
        add_sort(field_id, desc=False)|Sort  (desc=True for descending; ascending by default)

    * Common WarrantField field_id (full list see [WarrantField](./quote.md#9880)):

        field_id|Meaning|Filter type
        :-|:-|:-
        4|ISSUER_ID|choice
        5|STOCK_OWNER underlying|choice  (Accepts code strings like ["HK.00700"])
        6|WARRANT_TYPE|choice  (1=Call, 2=Put, 3=Bull, 4=Bear, 5=Inline; see [WarrantType](./quote.md#1724))
        8|CURRENT_PRICE|interval
        9|STREET_RATIO|interval
        10|VOLUME|interval
        16|LEVERAGE_RATIO|interval
        19|STATUS|choice  (0=Normal, 1=Suspended, 2=Pre-IPO; see [WarrantStatus](./quote.md#1724))
        23|EFFECTIVE_LEVERAGE|interval

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>When ret == RET_OK, returns (last_page, all_count, DataFrame)</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, an error description is returned</td>
        </tr>
    </table>

    * Returned DataFrame fields (45 columns total):

        Field|Type|Description
        :-|:-|:-
        issuer_id|int|Issuer ID
        warrant_type|int|Warrant type  (1=Call, 2=Put, 3=Bull, 4=Bear, 5=Inline)
        strike_price|float|Strike price
        maturity_date|str|Maturity date
        last_trade_date|str|Last trade date
        conversion_ratio|float|Conversion ratio
        last_close_price|float|Previous close price
        recovery_price|float|Recovery price (Bull/Bear only)
        stock_owner_price|float|Underlying stock price
        current_price|float|Current price
        volume|int|Volume
        turnover|float|Turnover
        sell_vol|int|Ask volume
        buy_vol|int|Bid volume
        sell_price|float|Ask price
        buy_price|float|Bid price
        street_rate|float|Street ratio
        high_price|float|High
        low_price|float|Low
        implied_volatility|float|Implied volatility (Call/Put only)
        delta|float|Delta (Call/Put only)
        status|int|Warrant status  (0=Normal, 1=Suspended, 2=Pre-IPO)
        street_rate_new|float|Street ratio (new)
        score|float|Composite score
        premium|float|Premium
        leverage|float|Leverage
        effective_leverage|float|Effective leverage
        break_even_point|float|Break-even point
        ipop|float|In/Out of the money
        amplitude|float|Amplitude
        fx_score|float|SG score
        ipo_time|str|IPO time
        street_vol|int|Street volume
        lot_size|int|Lot size
        issue_size|int|Issue size
        ipo_price|float|IPO price
        upper_strike_price|float|Upper strike price (Inline only)
        lower_strike_price|float|Lower strike price (Inline only)
        iw_price_status|int|Inside / outside the range
        sensitivity|float|Sensitivity
        price_recovery_ratio|float|Underlying distance to recovery price (Bull/Bear only)
        code|str|Warrant code with market prefix (e.g. HK.10001), filled by OpenD after symbol lookup
        owner_code|str|Underlying code with market prefix (e.g. HK.00700)
        name|str|Warrant name
        owner_name|str|Underlying name

* **Example**

```python
from moomoo import (
    OpenQuoteContext, RET_OK, WarrantScreenRequest,
    WarrantMarket, WarrantField, WarrantType,
)

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Example 1: HK low-priced high-leverage Call / Put warrants
req = WarrantScreenRequest(warrant_market=WarrantMarket.HK)
req.add_choice_filter(field_id=WarrantField.WARRANT_TYPE,
                      choices=[WarrantType.CALL, WarrantType.PUT])           # Call + Put
req.add_interval_filter(field_id=WarrantField.CURRENT_PRICE,
                        min_val=0.1, max_val=5.0)                            # Current price 0.1~5
req.add_interval_filter(field_id=WarrantField.EFFECTIVE_LEVERAGE,
                        min_val=3.0)                                         # Effective leverage > 3
req.add_interval_filter(field_id=WarrantField.STREET_RATIO, max_val=50.0)    # Street ratio < 50%
req.add_sort(field_id=WarrantField.VOLUME, desc=True)                        # Volume descending
req.page_count = 20

ret, data = quote_ctx.get_warrant_screen(req)
if ret == RET_OK:
    last_page, all_count, df = data
    print(df[['code', 'warrant_type', 'current_price', 'effective_leverage']].head())
else:
    print('error: ', data)

# Example 2: Return only the total count of matching records
req = WarrantScreenRequest(warrant_market=WarrantMarket.HK)
req.only_count = True
req.add_choice_filter(field_id=WarrantField.WARRANT_TYPE, choices=[WarrantType.CALL])
req.add_interval_filter(field_id=WarrantField.CURRENT_PRICE, min_val=1.0)
ret, data = quote_ctx.get_warrant_screen(req)
if ret == RET_OK:
    _, all_count, _ = data
    print(f"Total Call warrants matching: {all_count}")

# Example 3: Filter by underlying stock code (choice accepts code string)
req = WarrantScreenRequest(warrant_market=WarrantMarket.HK)
req.add_choice_filter(field_id=WarrantField.STOCK_OWNER, choices=["HK.00700"])
req.add_choice_filter(field_id=WarrantField.WARRANT_TYPE,
                      choices=[WarrantType.BULL, WarrantType.BEAR])          # Bull + Bear
req.add_sort(field_id=WarrantField.TURNOVER, desc=True)
req.page_count = 50
ret, data = quote_ctx.get_warrant_screen(req)
if ret == RET_OK:
    _, all_count, df = data
    print(f"Total Tencent bull/bear warrants: {all_count}")
    print(df[['code', 'name', 'warrant_type', 'turnover']].head())

quote_ctx.close()
```

* **Output**

```python
       code  warrant_type  current_price  effective_leverage
0  HK.29080             1          0.117               7.070
1  HK.28957             1          0.110               8.021
2  HK.28545             1          0.106               6.807
3  HK.29526             1          0.118               4.337
4  HK.13637             1          0.212               5.896
Total Call warrants matching: 197
Total Tencent bull/bear warrants: 393
       code               name  warrant_type    turnover
0  HK.57161  腾讯法兴六乙牛X.C             3  10149350.0
1  HK.54908  腾讯法兴六乙牛R.C             3   9797800.0
2  HK.55573  腾讯华泰六十牛C.C             3   4227400.0
3  HK.53663  腾讯法兴六乙牛N.C             3   3504625.0
4  HK.68433  腾讯法兴六乙牛M.C             3   3018900.0
```

* **Per-field examples**

    > All examples below assume `req = WarrantScreenRequest(warrant_market=WarrantMarket.HK)` has been constructed;
    > the measured response is OpenD HK-market sample data, showing the corresponding `all_count` and DataFrame head for that field (values already auto-scaled by the SDK).

    ##### `CODE`（id=1 · choice · HK · no return column） Security code (text)

    Pass an array of prefixed code strings (e.g. `"HK.57161"`); SDK auto-strips the prefix; exact match only

    ```python
    req.add_choice_filter(WarrantField.CODE, ["HK.57161", "HK.54908", "HK.55573"])
    ```

    Measured response (HK · all_count=3, 3 rows matched):

    ```
           code               name owner_code owner_name  warrant_type  current_price
    0  HK.54908  腾讯法兴六乙牛R.C   HK.00700   腾讯控股             3          0.066
    1  HK.55573  腾讯华泰六十牛C.C   HK.00700   腾讯控股             3          0.080
    2  HK.57161  腾讯法兴六乙牛X.C   HK.00700   腾讯控股             3          0.044
    ```

    ##### `NAME`（id=2 · choice/sort · HK · no return column） Security name (text)

    Text field, suitable only for sort; choice requires a name string

    ```python
    req.add_sort(WarrantField.NAME, desc=False)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.59177  阿里法巴八十熊G.P   HK.09988     阿里巴巴-W             4          0.290
    1  HK.65875  阿里法巴八十熊H.P   HK.09988     阿里巴巴-W             4          0.024
    2  HK.55774  阿里法巴八十熊I.P   HK.09988     阿里巴巴-W             4          0.203
    3  HK.60642  阿里法巴八五熊D.P   HK.09988     阿里巴巴-W             4          0.157
    4  HK.66020  阿里法巴八五熊E.P   HK.09988     阿里巴巴-W             4          0.173
    ```

    ##### `ISSUER_ID`（id=4 · choice · HK · return column `issuer_id`） Issuer ID

    Filterable only on HK; SG/MY measurements show issuer_id always 0. See the ISSUER_ID table above for the full issuer mapping

    ```python
    req.add_choice_filter(WarrantField.ISSUER_ID, [21])  # 仅瑞通 VT 发行
    req.add_sort(WarrantField.TURNOVER, desc=True)
    ```

    Measured response (HK · all_count=2431, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  issuer_id  warrant_type  current_price
    0  HK.55430  恒指瑞银八十熊B.P  HK.800000       恒生指数         21             4          0.053
    1  HK.57466  恒指瑞银八九牛N.C  HK.800000       恒生指数         21             3          0.037
    2  HK.27921  恒指瑞银六九沽A.P  HK.800000       恒生指数         21             2          0.050
    3  HK.29814  恒指瑞银六甲购A.C  HK.800000       恒生指数         21             1          0.052
    4  HK.56502  恒指瑞银八九牛D.C  HK.800000       恒生指数         21             3          0.054
    ```

    ##### `STOCK_OWNER`（id=5 · choice · HK / SG / MY · return column `owner_code`） Underlying stock ID

    Accepts a list of code strings directly, e.g. ["HK.00700"]

    ```python
    req.add_choice_filter(WarrantField.STOCK_OWNER, ["HK.00700"])
    req.add_sort(WarrantField.TURNOVER, desc=True)
    ```

    Measured response (HK · all_count=844, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.29080  腾讯国君六甲购B.C   HK.00700       腾讯控股             1          0.117
    1  HK.27892  腾讯摩通六九购E.C   HK.00700       腾讯控股             1          0.058
    2  HK.27966  腾讯法兴六九购D.C   HK.00700       腾讯控股             1          0.060
    3  HK.28957  腾讯法兴六甲购B.C   HK.00700       腾讯控股             1          0.110
    4  HK.29069  腾讯摩通六甲购B.C   HK.00700       腾讯控股             1          0.099
    ```

    ##### `WARRANT_TYPE`（id=6 · choice · HK / SG / MY · return column `warrant_type`） Warrant type

    1=Call 2=Put 3=Bull 4=Bear 5=Inline; SG measurements may return 6/7, MY may return 8 (not defined in the SDK enum)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE,
                          [WarrantType.BULL, WarrantType.BEAR])
    req.add_sort(WarrantField.TURNOVER, desc=True)
    ```

    Measured response (HK · all_count=7923, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数             4          0.056
    1  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数             3          0.038
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数             3          0.037
    3  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数             4          0.055
    4  HK.57114  恒指法兴八九牛7.C  HK.800000       恒生指数             3          0.054
    ```

    ##### `CONVERSION_RATIO`（id=7 · interval · HK / SG / MY · return column `conversion_ratio`） Conversion ratio

    SDK takes the ratio itself (pass 1.0 for a 1.0 ratio); protocol field ×1000 integer-encoded on the wire

    ```python
    req.add_interval_filter(WarrantField.CONVERSION_RATIO, min_val=1.0, max_val=10.0)
    req.add_sort(WarrantField.CONVERSION_RATIO, desc=False)
    ```

    Measured response (HK · all_count=3527, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  conversion_ratio  warrant_type  current_price
    0  HK.15938  利丰瑞信七七购A.C   HK.01818       招金矿业               1.0             1          0.000
    1  HK.15941  平安瑞银七甲沽B.P   HK.02318       中国平安               1.0             1          0.000
    2  HK.25738  首程麦银六八购A.C   HK.00697       首程控股               1.0             1          0.016
    3  HK.15190    中核信证六二购B   HK.01816      中广核电力               1.0             1          0.000
    4  HK.17771  置富麦银六八购A.C   HK.00778     置富产业信托               1.0             1          0.015
    ```

    ##### `CURRENT_PRICE`（id=8 · interval · HK / SG / MY · return column `current_price`） Current price

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.CURRENT_PRICE, min_val=0.1, max_val=0.15)
    req.add_sort(WarrantField.CURRENT_PRICE, desc=False)
    ```

    Measured response (HK · all_count=1719, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  current_price  warrant_type
    0  HK.65586  中移花旗六九牛C.C   HK.00941       中国移动            0.1             3
    1  HK.67749  阿里瑞银六六牛B.C   HK.09988     阿里巴巴-W            0.1             3
    2  HK.69293  港交汇丰七甲牛A.C   HK.00388      香港交易所            0.1             3
    3  HK.56800  恒指信证七九牛U.C  HK.800000       恒生指数            0.1             3
    4  HK.57184  恒指法兴八三牛A.C  HK.800000       恒生指数            0.1             3
    ```

    ##### `STREET_RATIO`（id=9 · interval · HK / SG / MY · return column `street_rate`） Street ratio

    Unit: %; SDK takes the value as e.g. 50.0 (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.STREET_RATIO, min_val=10.0, max_val=50.0)
    req.add_sort(WarrantField.STREET_RATIO, desc=False)
    ```

    Measured response (HK · all_count=1918, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  street_rate  warrant_type  current_price
    0  HK.27205  腾讯瑞银八乙购A.C   HK.00700       腾讯控股        10.00             1          0.233
    1  HK.63380  恒指中银八三熊I.P  HK.800000       恒生指数        10.00             4          0.335
    2  HK.60023  恒指国君七乙牛S.C  HK.800000       恒生指数        10.01             3          0.193
    3  HK.21640  飞鹤华泰六七购A.C   HK.06186       中国飞鹤        10.01             1          0.010
    4  HK.25461  恒指瑞银六七购A.C  HK.800000       恒生指数        10.01             1          0.010
    ```

    ##### `VOLUME`（id=10 · interval · HK / SG / MY · return column `volume`） Volume

    Unit: shares

    ```python
    req.add_interval_filter(WarrantField.VOLUME, min_val=1000)
    req.add_sort(WarrantField.VOLUME, desc=True)
    ```

    Measured response (HK · all_count=6092, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name       volume  warrant_type  current_price
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数  20257030000             4          0.056
    1  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数  18202610000             4          0.055
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数  17612080000             3          0.037
    3  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数  16576470000             3          0.038
    4  HK.55430  恒指瑞银八十熊B.P  HK.800000       恒生指数  12932700000             4          0.053
    ```

    ##### `MATURITY_DATE`（id=11 · interval · HK / SG / MY · return column `maturity_date`） Maturity date (Unix timestamp seconds)

    Unix timestamp in seconds; returned maturity_date is also a string-typed timestamp

    ```python
    import time
    req.add_interval_filter(WarrantField.MATURITY_DATE,
                            min_val=int(time.time()),
                            max_val=int(time.time()) + 365*86400)
    req.add_sort(WarrantField.MATURITY_DATE, desc=False)
    ```

    Measured response (HK · all_count=9330, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  maturity_date  warrant_type  current_price
    0  HK.21145  金云摩利六六购A.C   HK.03896        金山云     1781539200             1          0.010
    1  HK.54786  百度瑞银六六牛B.C   HK.09888    百度集团-SW     1781539200             3          0.305
    2  HK.23342  优必中银六六购B.C   HK.09880        优必选     1781539200             1          0.010
    3  HK.23574  汇量华泰六六购A.C   HK.01860       汇量科技     1781539200             1          0.010
    4  HK.18353  美高摩通六六购A.C   HK.02282      美高梅中国     1781625600             1          0.010
    ```

    ##### `STRIKE_PRICE`（id=12 · interval · HK / SG / MY · return column `strike_price`） Strike price

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.STRIKE_PRICE, min_val=10.0, max_val=20.0)
    req.add_sort(WarrantField.STRIKE_PRICE, desc=False)
    ```

    Measured response (HK · all_count=990, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  strike_price  warrant_type  current_price
    0  HK.19876  喜相华泰六八购A.C   HK.02473      喜相逢集团          10.0             1          0.010
    1  HK.23889  中油法巴六七购A.C   HK.00857     中国石油股份          10.0             1          0.153
    2  HK.11055  英港摩通六七沽A.P        N/A        N/A          10.0             2          0.051
    3  HK.25258  中联花旗六八购A.C   HK.00762       中国联通          10.0             1          0.014
    4  HK.27520  新发信证七三购A.C   HK.00017      新世界发展          10.0             1          0.107
    ```

    ##### `PREMIUM`（id=13 · interval · HK / SG / MY · return column `premium`） Premium

    Unit: %; SDK takes the value as e.g. 15.0, negative allowed (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.PREMIUM, min_val=0.0, max_val=20.0)
    req.add_sort(WarrantField.PREMIUM, desc=False)
    ```

    Measured response (HK · all_count=11283, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  premium  warrant_type  current_price
    0  HK.21137  恒大中银八七购A.C        N/A        N/A      0.0             1          0.000
    1  HK.16449  恒生中银九乙购A.C        N/A        N/A      0.0             1          0.000
    2  HK.16512  恒指高盛九九沽J.P   HK.06688       蚂蚁集团      0.0             1          0.000
    3  HK.16522  恒指瑞通九十沽A.P   HK.06688       蚂蚁集团      0.0             1          0.000
    4  HK.68392  招行瑞银六八牛A.C   HK.03968       招商银行      0.0             3          0.238
    ```

    ##### `RECOVERY_PRICE`（id=14 · interval · HK / SG / MY · return column `recovery_price`） Recovery price

    Unit: in currency; SDK takes the raw price; effective only for Bull/Bear (3/4) (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE,
                          [WarrantType.BULL, WarrantType.BEAR])
    req.add_interval_filter(WarrantField.RECOVERY_PRICE, min_val=0.01)
    req.add_sort(WarrantField.RECOVERY_PRICE, desc=False)
    ```

    Measured response (HK · all_count=7923, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  recovery_price  warrant_type  current_price
    0  HK.59404  商汤瑞银七八牛D.C   HK.00020       商汤-W            1.00             3          0.062
    1  HK.64826  商汤法兴七五牛A.C   HK.00020       商汤-W            1.05             3          0.113
    2  HK.59403  商汤瑞银七八牛C.C   HK.00020       商汤-W            1.10             3          0.053
    3  HK.64933  商汤瑞银六乙牛A.C   HK.00020       商汤-W            1.20             3          0.074
    4  HK.59322    商汤汇丰七一牛A   HK.00020       商汤-W            1.20             3          0.000
    ```

    ##### `IMPLIED_VOLATILITY`（id=15 · interval · HK / SG / MY · return column `implied_volatility`） Implied volatility

    Unit: %; SDK takes the value as e.g. 15.0; effective only for Call/Put (1/2) (protocol field ×100 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.IMPLIED_VOLATILITY, min_val=10.0, max_val=100.0)
    req.add_sort(WarrantField.IMPLIED_VOLATILITY, desc=False)
    ```

    Measured response (HK · all_count=5962, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  implied_volatility  warrant_type  current_price
    0  HK.24413  中移中银六九购A.C   HK.00941       中国移动              13.487             1          0.041
    1  HK.25984  建行韩投八乙购A.C   HK.00939       建设银行              14.638             1          0.500
    2  HK.25450  中移国君六九购A.C   HK.00941       中国移动              15.308             1          0.054
    3  HK.24942  中移汇丰六九购A.C   HK.00941       中国移动              15.776             1          0.059
    4  HK.14414  建行法巴六乙购A.C   HK.00939       建设银行              15.792             1          0.191
    ```

    ##### `LEVERAGE_RATIO`（id=16 · interval · HK / SG / MY · return column `leverage`） Leverage ratio

    SDK takes the raw value (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.LEVERAGE_RATIO, min_val=3.0, max_val=50.0)
    req.add_sort(WarrantField.LEVERAGE_RATIO, desc=True)
    ```

    Measured response (HK · all_count=8360, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  leverage  warrant_type  current_price
    0  HK.29999  恒指中银六乙购C.C  HK.800000       恒生指数    49.985             1          0.071
    1  HK.27121  领展瑞银六九购A.C   HK.00823     领展房产基金    49.972             1          0.074
    2  HK.15343  百度摩通六八沽A.P   HK.09888    百度集团-SW    49.869             2          0.023
    3  HK.25973  远能麦银六八购A.C   HK.01138       中远海能    49.852             1          0.068
    4  HK.26365  远能麦银六九购A.C   HK.01138       中远海能    49.852             1          0.034
    ```

    ##### `PRICE_RECOVERY_RATIO`（id=17 · interval · HK / SG / MY · return column `price_recovery_ratio`） Underlying-to-recovery price %

    Unit: %; SDK takes the value as e.g. 15.0, negative allowed; effective only for Bull/Bear (3/4) (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE,
                          [WarrantType.BULL, WarrantType.BEAR])
    req.add_interval_filter(WarrantField.PRICE_RECOVERY_RATIO,
                            min_val=-50.0, max_val=50.0)
    req.add_sort(WarrantField.PRICE_RECOVERY_RATIO, desc=False)
    ```

    Measured response (HK · all_count=7923, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  price_recovery_ratio  warrant_type  current_price
    0  HK.54832  美团瑞银七乙熊M.P   HK.03690       美团-W              -0.73916             4          0.430
    1  HK.53329  美团瑞银七乙熊I.P   HK.03690       美团-W              -0.72053             4          0.390
    2  HK.54269  美团摩通七九熊F.P   HK.03690       美团-W              -0.72053             4          0.395
    3  HK.54562  美团汇丰七乙熊D.P   HK.03690       美团-W              -0.71018             4          0.370
    4  HK.54799  美团摩通七乙熊D.P   HK.03690       美团-W              -0.71018             4          0.370
    ```

    ##### `DELTA`（id=18 · interval · HK / SG / MY · return column `delta`） Delta

    SDK takes the raw value, range [-1, 1]; effective only for Call/Put (1/2) (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE,
                          [WarrantType.CALL, WarrantType.PUT])
    req.add_interval_filter(WarrantField.DELTA, min_val=-1.0, max_val=1.0)
    req.add_sort(WarrantField.DELTA, desc=True)
    ```

    Measured response (HK · all_count=8247, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  delta  warrant_type  current_price
    0  HK.16281  联想信证六六购A.C   HK.00992       联想集团  0.999             1           1.28
    1  HK.18636  中寿国君六六购A.C   HK.02628       中国人寿  0.999             1           0.59
    2  HK.22934  建滔华泰六八购A.C   HK.00148       建滔集团  0.997             1           6.73
    3  HK.19057  汇丰摩利六七购A.C   HK.00005       汇丰控股  0.996             1           0.87
    4  HK.19058  汇丰法兴六七购A.C   HK.00005       汇丰控股  0.996             1           0.87
    ```

    ##### `STATUS`（id=19 · choice · HK / SG / MY · return column `status`） Warrant status

    0=Normal 1=Terminated 2=Pending listing

    ```python
    req.add_choice_filter(WarrantField.STATUS, [WarrantStatus.NORMAL])
    req.add_sort(WarrantField.VOLUME, desc=True)
    ```

    Measured response (HK · all_count=13057, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  status  warrant_type  current_price
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数       0             4          0.056
    1  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数       0             4          0.055
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数       0             3          0.037
    3  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数       0             3          0.038
    4  HK.55430  恒指瑞银八十熊B.P  HK.800000       恒生指数       0             4          0.053
    ```

    ##### `IPO_TIME`（id=20 · interval · HK / SG / MY · return column `ipo_time`） Listing time (Unix timestamp seconds)

    Unix timestamp in seconds

    ```python
    req.add_interval_filter(WarrantField.IPO_TIME,
                            min_val=1700000000, max_val=2000000000)
    req.add_sort(WarrantField.IPO_TIME, desc=True)
    ```

    Measured response (HK · all_count=16122, 5 rows matched, head top 5):

    ```
           code      name owner_code owner_name    ipo_time  warrant_type  current_price
    0  HK.11203  道指摩通六乙沽B    US..DJI      道琼斯指数  1781625600             2            0.0
    1  HK.11204  纳指摩通六乙沽C    US..NDX  纳斯达克100指数  1781625600             2            0.0
    2  HK.11205  道指摩通六乙沽C    US..DJI      道琼斯指数  1781625600             2            0.0
    3  HK.13826  老铺摩利六乙沽A   HK.06181       老铺黄金  1781625600             2            0.0
    4  HK.13827  港交摩利六乙沽A   HK.00388      香港交易所  1781625600             2            0.0
    ```

    ##### `BUY_VOL`（id=21 · interval · HK / SG / MY · return column `buy_vol`） Buy volume

    Unit: shares

    ```python
    req.add_interval_filter(WarrantField.BUY_VOL, min_val=1)
    req.add_sort(WarrantField.BUY_VOL, desc=True)
    ```

    Measured response (HK · all_count=10554, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name   buy_vol  warrant_type  current_price
    0  HK.56746  恒指汇丰八甲牛V.C  HK.800000       恒生指数  41410000             3          0.065
    1  HK.56560  恒指摩通八三牛G.C  HK.800000       恒生指数  40730000             3          0.114
    2  HK.63929  恒指摩利八十牛E.C  HK.800000       恒生指数  40380000             3          0.102
    3  HK.64852  恒指瑞银八十牛G.C  HK.800000       恒生指数  40000000             3          0.131
    4  HK.29035  泡玛星展六甲沽A.P   HK.09992       泡泡玛特  40000000             2          0.071
    ```

    ##### `SELL_VOL`（id=22 · interval · HK / SG / MY · return column `sell_vol`） Sell volume

    Unit: shares

    ```python
    req.add_interval_filter(WarrantField.SELL_VOL, min_val=1)
    req.add_sort(WarrantField.SELL_VOL, desc=True)
    ```

    Measured response (HK · all_count=11581, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  sell_vol  warrant_type  current_price
    0  HK.26774  阿里法巴六七购B.C   HK.09988     阿里巴巴-W  60130000             1          0.010
    1  HK.29035  泡玛星展六甲沽A.P   HK.09992       泡泡玛特  37900000             2          0.071
    2  HK.55588  恒指汇丰九四熊D.P  HK.800000       恒生指数  34110000             4          0.055
    3  HK.56458  恒指摩通八九牛4.C  HK.800000       恒生指数  33830000             3          0.064
    4  HK.57114  恒指法兴八九牛7.C  HK.800000       恒生指数  33370000             3          0.054
    ```

    ##### `EFFECTIVE_LEVERAGE`（id=23 · interval · HK / SG / MY · return column `effective_leverage`） Effective leverage

    SDK takes the raw value (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.EFFECTIVE_LEVERAGE, min_val=3.0, max_val=50.0)
    req.add_sort(WarrantField.EFFECTIVE_LEVERAGE, desc=True)
    ```

    Measured response (HK · all_count=5409, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  effective_leverage  warrant_type  current_price
    0  HK.23821  建行国君六六购A.C   HK.00939       建设银行              47.082             1          0.102
    1  HK.25486  华地信证六六购B.C   HK.01109       华润置地              45.821             1          0.010
    2  HK.23727  领展信证六六购A.C   HK.00823     领展房产基金              44.375             1          0.012
    3  HK.23398  建行麦银六六购A.C   HK.00939       建设银行              42.977             1          0.017
    4  HK.23575  华地摩通六六购A.C   HK.01109       华润置地              42.093             1          0.012
    ```

    ##### `LAST_CLOSE_PRICE`（id=24 · interval · HK / SG / MY · return column `last_close_price`） Previous close

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.LAST_CLOSE_PRICE, min_val=0.1, max_val=2.0)
    req.add_sort(WarrantField.LAST_CLOSE_PRICE, desc=False)
    ```

    Measured response (HK · all_count=7028, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  last_close_price  warrant_type  current_price
    0  HK.14210  腾讯花旗六乙沽A.P   HK.00700       腾讯控股               0.1             2          0.101
    1  HK.67749  阿里瑞银六六牛B.C   HK.09988     阿里巴巴-W               0.1             3          0.100
    2  HK.53182  平安汇丰七甲牛L.C   HK.02318       中国平安               0.1             3          0.107
    3  HK.69230  平安法兴七十牛U.C   HK.02318       中国平安               0.1             3          0.105
    4  HK.56325  恒指法兴八三牛8.C  HK.800000       恒生指数               0.1             3          0.119
    ```

    ##### `TURNOVER`（id=25 · interval · HK / SG / MY · return column `turnover`） Turnover

    Unit: in currency

    ```python
    req.add_interval_filter(WarrantField.TURNOVER, min_val=1)
    req.add_sort(WarrantField.TURNOVER, desc=True)
    ```

    Measured response (HK · all_count=6093, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name     turnover  warrant_type  current_price
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数  864568920.0             4          0.056
    1  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数  852463370.0             3          0.038
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数  842853250.0             3          0.037
    3  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数  777372600.0             4          0.055
    4  HK.57114  恒指法兴八九牛7.C  HK.800000       恒生指数  608277730.0             3          0.054
    ```

    ##### `SELL_PRICE`（id=26 · interval · HK / SG / MY · return column `sell_price`） Ask price

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.SELL_PRICE, min_val=0.001)
    req.add_sort(WarrantField.SELL_PRICE, desc=False)
    ```

    Measured response (HK · all_count=11581, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  sell_price  warrant_type  current_price
    0  HK.23665  S金摩通六七购A.C   HK.02840      SPDR金        0.01             1           0.01
    1  HK.25680  百度麦银六七购A.C   HK.09888    百度集团-SW        0.01             1           0.01
    2  HK.27365  中交法兴六六购A.C   HK.01800     中国交通建设        0.01             1           0.01
    3  HK.28314  铁塔信证六九购A.C   HK.00788       中国铁塔        0.01             1           0.01
    4  HK.28806  协鑫麦银六九购A.C   HK.03800       协鑫科技        0.01             1           0.01
    ```

    ##### `BUY_PRICE`（id=27 · interval · HK / SG / MY · return column `buy_price`） Bid price

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.BUY_PRICE, min_val=0.001)
    req.add_sort(WarrantField.BUY_PRICE, desc=False)
    ```

    Measured response (HK · all_count=10554, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  buy_price  warrant_type  current_price
    0  HK.13598  小米摩通六乙购B.C   HK.01810     小米集团-W       0.01             1          0.010
    1  HK.14635  比迪星展六甲购A.C   HK.01211      比亚迪股份       0.01             1          0.010
    2  HK.14652  腾讯法兴六九购A.C   HK.00700       腾讯控股       0.01             1          0.011
    3  HK.16396  南科信证六乙购A.C   HK.03033     南方恒生科技       0.01             1          0.014
    4  HK.17724  泡玛汇丰六甲购A.C   HK.09992       泡泡玛特       0.01             1          0.012
    ```

    ##### `HIGH_PRICE`（id=28 · interval · HK / SG / MY · return column `high_price`） High price

    Unit: in currency; SDK takes the raw price; intraday high (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.HIGH_PRICE, min_val=0.001)
    req.add_sort(WarrantField.HIGH_PRICE, desc=True)
    ```

    Measured response (HK · all_count=6075, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  high_price  warrant_type  current_price
    0  HK.11115  美光法兴六甲购A.C        N/A        N/A        6.74             1           6.74
    1  HK.24047  建板摩利六七购A.C   HK.01888      建滔积层板        6.47             1           6.47
    2  HK.25060  建滔华泰六八购B.C   HK.00148       建滔集团        5.67             1           5.65
    3  HK.16544  建板信证六十购A.C   HK.01888      建滔积层板        5.57             1           5.57
    4  HK.26175  建板汇丰六八购A.C   HK.01888      建滔积层板        5.44             1           5.44
    ```

    ##### `LOW_PRICE`（id=29 · interval · HK / SG / MY · return column `low_price`） Low price

    Unit: in currency; SDK takes the raw price; intraday low (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.LOW_PRICE, min_val=0.001)
    req.add_sort(WarrantField.LOW_PRICE, desc=False)
    ```

    Measured response (HK · all_count=6075, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  low_price  warrant_type  current_price
    0  HK.28933  阿里麦银六七购A.C   HK.09988     阿里巴巴-W       0.01             1           0.01
    1  HK.29014  阿里法兴六六购A.C   HK.09988     阿里巴巴-W       0.01             1           0.01
    2  HK.13598  小米摩通六乙购B.C   HK.01810     小米集团-W       0.01             1           0.01
    3  HK.13662  中联麦银六九购A.C   HK.00762       中国联通       0.01             1           0.01
    4  HK.14148  腾讯汇丰六七购A.C   HK.00700       腾讯控股       0.01             1           0.01
    ```

    ##### `RATIO_ITM_OTM`（id=30 · interval · HK / SG / MY · return column `ipop`） ITM/OTM ratio %

    Unit: %; SDK takes the value as e.g. 15.0, negative allowed; returned column name is ipop (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.RATIO_ITM_OTM, min_val=-50.0, max_val=50.0)
    req.add_sort(WarrantField.RATIO_ITM_OTM, desc=False)
    ```

    Measured response (HK · all_count=16166, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name      ipop  warrant_type  current_price
    0  HK.21173  信达海通八七购A.C   HK.01359       中国信达 -41.74285             1          0.000
    1  HK.21158  华泥瑞信八七购A.C   HK.01313     华润建材科技 -41.68907             1          0.000
    2  HK.25100  喜相摩通六六购A.C   HK.02473      喜相逢集团 -37.67187             1          0.061
    3  HK.25841  喜相麦银六七购A.C   HK.02473      喜相逢集团 -37.64062             1          0.025
    4  HK.15946  信达瑞信七六购A.C   HK.01359       中国信达 -37.40952             1          0.000
    ```

    ##### `BREAK_EVEN_POINT`（id=31 · interval · HK / SG / MY · return column `break_even_point`） Break-even point %

    Unit: %; SDK takes the value as e.g. 15.0 (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.BREAK_EVEN_POINT, min_val=-100.0, max_val=100.0)
    req.add_sort(WarrantField.BREAK_EVEN_POINT, desc=False)
    ```

    Measured response (HK · all_count=11618, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  break_even_point  warrant_type  current_price
    0  HK.21137  恒大中银八七购A.C        N/A        N/A               0.0             1          0.000
    1  HK.16449  恒生中银九乙购A.C        N/A        N/A               0.0             1          0.000
    2  HK.49942  道指汇丰六乙熊H.P    US..DJI      道琼斯指数               0.0             4          0.013
    3  HK.49950  道指瑞银六乙熊L.P    US..DJI      道琼斯指数               0.0             4          0.012
    4  HK.29859  东风麦银六六购A.C        N/A        N/A               0.0             1          0.720
    ```

    ##### `AMPLITUDE`（id=32 · interval · HK / SG / MY · return column `amplitude`） Amplitude %

    Unit: %; SDK takes the value as e.g. 15.0 (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.AMPLITUDE, min_val=0.01)
    req.add_sort(WarrantField.AMPLITUDE, desc=True)
    ```

    Measured response (HK · all_count=5358, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  amplitude  warrant_type  current_price
    0  HK.23936  舜光信证六六购A.C   HK.02382     舜宇光学科技    3.80000             1          0.054
    1  HK.23432  舜光摩利六六购A.C   HK.02382     舜宇光学科技    3.27273             1          0.055
    2  HK.24022  舜光花旗六六购A.C   HK.02382     舜宇光学科技    3.00000             1          0.058
    3  HK.20335  江铜摩通六六购A.C   HK.00358     江西铜业股份    2.24390             1          0.181
    4  HK.61517  中芯法兴六甲牛H.C   HK.00981       中芯国际    2.00000             3          0.076
    ```

    ##### `SCORE_FAXING`（id=33 · interval · HK / SG / MY · return column `fx_score`） SG Faxing score

    SDK takes the raw score; returned column name is fx_score (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.SCORE_FAXING, min_val=0.0, max_val=10.0)
    req.add_sort(WarrantField.SCORE_FAXING, desc=True)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  fx_score  warrant_type  current_price
    0  HK.29442  中药法巴七五购A.C   HK.01177     中国生物制药   0.94860             1          0.071
    1  HK.13660  建滔法兴七一购B.C   HK.00148       建滔集团   0.94397             1          0.193
    2  HK.29636  美图摩通六甲购A.C   HK.01357       美图公司   0.93674             1          0.127
    3  HK.24961  中移摩通六九购A.C   HK.00941       中国移动   0.93553             1          0.070
    4  HK.21241  兖矿摩通六八购A.C   HK.01171       兖矿能源   0.93449             1          0.202
    ```

    ##### `LAST_TRADE_DATE`（id=34 · interval · HK / SG / MY · return column `last_trade_date`） Last trading day (Unix timestamp seconds)

    Unix timestamp in seconds; typically 1 trading day earlier than MATURITY_DATE

    ```python
    req.add_interval_filter(WarrantField.LAST_TRADE_DATE,
                            min_val=1900000000, max_val=2200000000)
    req.add_sort(WarrantField.LAST_TRADE_DATE, desc=False)
    ```

    Measured response (HK · all_count=1, 1 rows matched, head top 5):

    ```
           code        name owner_code owner_name  last_trade_date  warrant_type  current_price
    0  HK.29183  建行法巴零乙购A.C   HK.00939       建设银行       1924272000             1          0.237
    ```

    ##### `STREET_VOLUME`（id=35 · interval · HK / SG / MY · return column `street_vol`） Street volume

    Unit: shares; returned column name is street_vol

    ```python
    req.add_interval_filter(WarrantField.STREET_VOLUME, min_val=1)
    req.add_sort(WarrantField.STREET_VOLUME, desc=True)
    ```

    Measured response (HK · all_count=11611, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  street_vol  warrant_type  current_price
    0  HK.14958  腾讯法兴六七购A.C   HK.00700       腾讯控股   400000000             1          0.010
    1  HK.14826  腾讯摩通六七购A.C   HK.00700       腾讯控股   398760000             1          0.010
    2  HK.25097  腾讯摩通六九购A.C   HK.00700       腾讯控股   319360000             1          0.012
    3  HK.13039  小米摩通六乙购A.C   HK.01810     小米集团-W   306960000             1          0.017
    4  HK.14148  腾讯汇丰六七购A.C   HK.00700       腾讯控股   300000000             1          0.010
    ```

    ##### `LOT_SIZE`（id=36 · interval · HK / SG / MY · return column `lot_size`） Lot size

    Unit: shares

    ```python
    req.add_interval_filter(WarrantField.LOT_SIZE, min_val=1)
    req.add_sort(WarrantField.LOT_SIZE, desc=False)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  lot_size  warrant_type  current_price
    0  HK.22588  万科麦银六六购B.C   HK.02202       万科企业       100             1          0.010
    1  HK.24402  航赁麦银六七购A.C   HK.02588     中银航空租赁       100             1          0.019
    2  HK.24702  航赁华泰六七购A.C   HK.02588     中银航空租赁       100             1          0.010
    3  HK.27072  蔚来麦银六九沽A.P   HK.09866      蔚来-SW       100             2          0.071
    4  HK.19866  南科华泰六六购A.C   HK.03033     南方恒生科技       200             1          0.010
    ```

    ##### `ISSUE_SIZE`（id=37 · interval · HK / SG / MY · return column `issue_size`） Issue size

    Unit: shares

    ```python
    req.add_interval_filter(WarrantField.ISSUE_SIZE, min_val=1)
    req.add_sort(WarrantField.ISSUE_SIZE, desc=True)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  issue_size  warrant_type  current_price
    0  HK.22659  阿里韩投八乙购A.C   HK.09988     阿里巴巴-W   500000000             1          0.370
    1  HK.16737  宁德法兴七乙购A.C   HK.03750       宁德时代   500000000             1          0.880
    2  HK.13850    恒指摩通六乙沽C  HK.800000       恒生指数   500000000             2          0.000
    3  HK.22235  港交韩投八八购A.C   HK.00388      香港交易所   480000000             1          0.325
    4  HK.22254  中移韩投八八购A.C   HK.00941       中国移动   480000000             1          0.162
    ```

    ##### `IPO_PRICE`（id=38 · interval · HK / SG / MY · return column `ipo_price`） IPO price

    Unit: in currency; SDK takes the raw price (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.IPO_PRICE, min_val=0.001)
    req.add_sort(WarrantField.IPO_PRICE, desc=False)
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: OpenD measurements show ipo_price returns 0 for most warrants, so min_val=0.001 filters out all rows

    ##### `LOWER_STRIKE_PRICE`（id=39 · interval · HK / SG / MY · return column `lower_strike_price`） Lower strike price

    Unit: in currency; SDK takes the raw price; effective only for Inline (5) (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE, [WarrantType.IW])
    req.add_interval_filter(WarrantField.LOWER_STRIKE_PRICE, min_val=0.001)
    req.add_sort(WarrantField.LOWER_STRIKE_PRICE, desc=False)
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No inline warrants (IW) are currently listed on HK; the warrant-type filter returns no rows

    ##### `UPPER_STRIKE_PRICE`（id=40 · interval · HK / SG / MY · return column `upper_strike_price`） Upper strike price

    Unit: in currency; SDK takes the raw price; effective only for Inline (5) (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE, [WarrantType.IW])
    req.add_interval_filter(WarrantField.UPPER_STRIKE_PRICE, min_val=0.001)
    req.add_sort(WarrantField.UPPER_STRIKE_PRICE, desc=False)
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No inline warrants (IW) are currently listed on HK; the warrant-type filter returns no rows

    ##### `IW_PRICE_STATUS`（id=41 · choice · HK / SG / MY · return column `iw_price_status`） Inside/outside the band

    0=Outside 1=Inside; only Inline (5) returns non-zero values

    ```python
    req.add_choice_filter(WarrantField.WARRANT_TYPE, [WarrantType.IW])
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No inline warrants (IW) are currently listed on HK; the warrant-type filter returns no rows

    ##### `SENSITIVITY`（id=42 · interval · HK / SG / MY · return column `sensitivity`） Sensitivity

    SDK takes the raw value (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.SENSITIVITY, min_val=0.001)
    req.add_sort(WarrantField.SENSITIVITY, desc=False)
    ```

    Measured response (HK · all_count=13623, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  sensitivity  warrant_type  current_price
    0  HK.19340  腾音信证六九购A.C   HK.01698    腾讯音乐-SW        0.018             1          0.010
    1  HK.28495  稀宇麦银六十购B.C   HK.00100  MINIMAX-W        0.019             1          0.013
    2  HK.51984  美团瑞银七乙熊G.P   HK.03690       美团-W        0.020             4          0.275
    3  HK.52261  美团法巴七七熊K.P   HK.03690       美团-W        0.020             4          0.280
    4  HK.52532  美团瑞银七乙熊H.P   HK.03690       美团-W        0.020             4          0.310
    ```

    ##### `CONVERSION_PRICE`（id=43 · interval · HK / SG / MY · no return column） Conversion price

    Not exposed separately in the returned DataFrame; usable as a filter / sort condition

    ```python
    req.add_interval_filter(WarrantField.CONVERSION_PRICE, min_val=0.001)
    req.add_sort(WarrantField.CONVERSION_PRICE, desc=False)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.64814  平安瑞银八三牛A.C   HK.02318       中国平安             3            0.0
    1  HK.15946  信达瑞信七六购A.C   HK.01359       中国信达             1            0.0
    2  HK.24719    腾讯东亚九四沽A   HK.00700       腾讯控股             2            0.0
    3  HK.26168    金软瑞银九二购B   HK.03888       金山软件             1            0.0
    4  HK.64492  恒指汇丰八五熊G.P  HK.800000       恒生指数             3            0.0
    ```

    ##### `CHANGE_RATE`（id=44 · interval · HK / SG / MY · no return column） Change rate %

    Unit: %; SDK takes the value as e.g. 5.0; not exposed separately in the returned DataFrame (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.CHANGE_RATE, min_val=-100.0, max_val=100.0)
    req.add_sort(WarrantField.CHANGE_RATE, desc=True)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.25160  远能华泰六七购B.C   HK.01138       中远海能             1          0.136
    1  HK.23936  舜光信证六六购A.C   HK.02382     舜宇光学科技             1          0.054
    2  HK.25876  远能华泰六八购A.C   HK.01138       中远海能             1          0.093
    3  HK.23432  舜光摩利六六购A.C   HK.02382     舜宇光学科技             1          0.055
    4  HK.26285  远能华泰六九购B.C   HK.01138       中远海能             1          0.048
    ```

    ##### `CHANGE_VALUE`（id=45 · interval · HK / SG / MY · no return column） Change value

    Unit: in currency; not exposed separately in the returned DataFrame

    ```python
    req.add_interval_filter(WarrantField.CHANGE_VALUE, min_val=-1.0, max_val=1.0)
    req.add_sort(WarrantField.CHANGE_VALUE, desc=True)
    ```

    Measured response (HK · all_count=7641, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.25336  铁塔摩利六乙购A.C   HK.00788       中国铁塔             1          0.017
    1  HK.25366  铁塔摩通六乙购A.C   HK.00788       中国铁塔             1          0.028
    2  HK.26138  铁塔中银六乙购A.C   HK.00788       中国铁塔             1          0.027
    3  HK.26447  中铁法兴六九购A.C   HK.00390       中国中铁             1          0.020
    4  HK.67330  京东摩通六乙牛A.C   HK.09618    京东集团-SW             3          0.216
    ```

    ##### `SCORE`（id=51 · interval · HK / SG / MY · return column `score`） Warrant score

    Composite score; SDK takes the raw score (protocol field ×100000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.SCORE, min_val=0.0, max_val=10.0)
    req.add_sort(WarrantField.SCORE, desc=True)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  score  warrant_type  current_price
    0  HK.11048  澳港摩通六七购A.C        N/A        N/A  0.010             1          0.195
    1  HK.11056  欧港摩通六七购A.C        N/A        N/A  0.009             1          0.016
    2  HK.49582  标指摩通六九牛B.C    US..SPX    标普500指数  0.009             3          0.193
    3  HK.10087  美日摩通六六购A.C  FX.USDJPY      美元/日元  0.008             1          0.073
    4  HK.11047  澳港摩通六七沽A.P        N/A        N/A  0.008             2          0.013
    ```

    ##### `FILTER_NO_TRADE`（id=52 · choice · HK / SG / MY · return column `current_price`） Filter out no-trade warrants

    Switch field: 0=no filter, 1=filter out warrants with zero volume; no data column returned

    ```python
    req.add_choice_filter(WarrantField.FILTER_NO_TRADE, [1])
    req.add_sort(WarrantField.VOLUME, desc=True)
    ```

    Measured response (HK · all_count=15151, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  current_price  warrant_type
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数          0.056             4
    1  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数          0.055             4
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数          0.037             3
    3  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数          0.038             3
    4  HK.55430  恒指瑞银八十熊B.P  HK.800000       恒生指数          0.053             4
    ```

    ##### `CURRENCY_CODE`（id=53 · choice · HK / SG / MY · no return column） Currency code

    Usually determined by market (HK=HKD, SG=SGD, MY=MYR); not exposed separately in the returned DataFrame

    ```python
    req.add_sort(WarrantField.TURNOVER, desc=True)
    ```

    Measured response (HK · all_count=16170, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  warrant_type  current_price
    0  HK.55994  恒指摩通九三熊R.P  HK.800000       恒生指数             4          0.056
    1  HK.57003  恒指摩通八九牛8.C  HK.800000       恒生指数             3          0.038
    2  HK.57109  恒指法兴八七牛E.C  HK.800000       恒生指数             3          0.037
    3  HK.55641  恒指法兴八三熊P.P  HK.800000       恒生指数             4          0.055
    4  HK.57114  恒指法兴八九牛7.C  HK.800000       恒生指数             3          0.054
    ```

    ##### `STOCK_OWNER_PRICE`（id=54 · interval · HK / SG / MY · return column `stock_owner_price`） Underlying stock price

    Unit: in currency; SDK takes the raw price; returned in the stock_owner_price column (protocol field ×1000 integer-encoded on the wire)

    ```python
    req.add_interval_filter(WarrantField.STOCK_OWNER_PRICE, min_val=0.001)
    req.add_sort(WarrantField.STOCK_OWNER_PRICE, desc=False)
    ```

    Measured response (HK · all_count=16168, 5 rows matched, head top 5):

    ```
           code        name owner_code owner_name  stock_owner_price  warrant_type  current_price
    0  HK.16376  碧桂法巴九十购A.C   HK.02007        碧桂园              0.209             1          0.000
    1  HK.16468  中粮麦银九甲购A.C   HK.00606       中骏商管              0.295             1          0.000
    2  HK.19876  喜相华泰六八购A.C   HK.02473      喜相逢集团              0.640             1          0.010
    3  HK.25841  喜相麦银六七购A.C   HK.02473      喜相逢集团              0.640             1          0.025
    4  HK.29782  喜相华泰六六购A.C   HK.02473      喜相逢集团              0.640             1          0.010
    ```

:::tip Interface Limitations
* A maximum of 60 requests per 30 seconds
:::

---

# Get Related Data of a Specific Security

`get_referencestock_list(code, reference_type)`

* **Description**

    Get related data of securities, such as: obtaining warrants related to underlying stocks, obtaining contracts related to futures

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code.
    reference_type|[SecurityReferenceType](./quote.md#8136)|Related data type to be obtained.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, related data of security is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Related data of security fotmat as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Security code.
        lot_size|int|The number of shares per lot, contract multiplier for futures.
        stock_type|[SecurityType](./quote.md#9767)|Security type.
        stock_name|str|Security name.
        list_time|str|Time of listing.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        wrt_valid|bool|Whether it is a warrant.  (If it is True, the following field start with 'wrt' is valid.)
        wrt_type|[WrtType](./quote.md#2421)|Warrant type.
        wrt_code|str|The underlying stock.
        future_valid|bool|Whether it is a future.  (If it is True, the following field start with 'future' is valid.)
        future_main_contract|bool|Whether the future main contract.  (Special field for futures.)
        future_last_trade_time|str|Last trading time.  (The field is unique to futures. Main, current month and next month futures do not have this field.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Get warrants related to the underlying stock
ret, data = quote_ctx.get_referencestock_list('HK.00700', SecurityReferenceType.WARRANT)
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['code'].values.tolist()) # Convert to list
else:
    print('error:', data)
print('******************************************')
# Port related contracts
ret, data = quote_ctx.get_referencestock_list('HK.A50main', SecurityReferenceType.FUTURE)
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['code'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
        code  lot_size stock_type stock_name   list_time  wrt_valid wrt_type  wrt_code  future_valid  future_main_contract  future_last_trade_time
0     HK.24719      1000    WARRANT     TENGXUNDONGYAJIUSIGUA  2018-07-20       True      PUT  HK.00700         False                   NaN                     NaN
...        ...       ...        ...        ...         ...        ...      ...       ...           ...                   ...                     ...
1617  HK.63402     10000    WARRANT     GS#TENCTRC2108Y  2020-11-26       True     BULL  HK.00700         False                   NaN                     NaN

[1618 rows x 11 columns]
HK.24719
['HK.24719', 'HK.27886', 'HK.28621', 'HK.14339', 'HK.27952', 'HK.18693', 'HK.20306', 'HK.53635', 'HK.47269', 'HK.27227', 
...        ...       ...        ...        ...         ...        ...      ...       ... 
'HK.63402']
******************************************
        code  lot_size stock_type         stock_name list_time  wrt_valid  wrt_type  wrt_code  future_valid  future_main_contract future_last_trade_time
0  HK.A50main      5000     FUTURE      A50 Future Main(DEC0)                False       NaN       NaN          True                  True                        
..         ...       ...        ...                ...       ...        ...       ...       ...           ...                   ...                    ...
5  HK.A502106      5000     FUTURE      A50 JUN1                False       NaN       NaN          True                 False             2021-06-29

[6 rows x 11 columns]
HK.A50main
['HK.A50main', 'HK.A502011', 'HK.A502012', 'HK.A502101', 'HK.A502103', 'HK.A502106']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* When obtaining warrants related to the underlying stock, it is not subject to the above frequency restriction
:::

---

# Get Futures Contract Information

`get_future_info(code_list)`

* **Description**

    Get futures contract information

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|Futures code list. Data type of elements in the list is str.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, futures contract data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Futures contract data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Future code.
        name|str|Future name.
        owner|str|Subject.
        exchange|str|Exchange.
        type|str|Contract type.
        size|float|Contract size.
        size_unit|str|Contract size unit.
        price_currency|str|Quote currency.
        price_unit|str|Price unit.
        min_change|float|Price change step.
        min_change_unit|str|Unit of price change step. (Obsolete field.)
        trade_time|str|Trading time.
        time_zone|str|Time zone.
        last_trade_time|str|The last trading time.  (Main, current month and next month futures do not have this field.)
        exchange_format_url|str|Exchange format url address.
        origin_code|str|Original future code.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_future_info(["HK.MPImain", "HK.HAImain"])
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['code'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code      name       owner exchange  type     size size_unit price_currency price_unit  min_change min_change_unit                        trade_time time_zone last_trade_time                                exchange_format_url           origin_code
0  HK.MPImain  MPI Future Main(NOV0)    Hang Seng Mainland Properties Index     HKEX  Equity Index     50.0  Index Points×HKD            HKD  Index Point        0.50       (09:15 - 12:00), (13:00 - 16:30)       CCT                  https://www.hkex.com.hk/Products/Listed-Deriva...           HK.MPI2112
1  HK.HAImain  HAI Future Main(NOV0)    HK.06837     HKEX  Single Stock  10000.0            shares            HKD  1 share/HKD        0.01               (09:30 - 12:00), (13:00 - 16:00)       CCT                  https://www.hkex.com.hk/Products/Listed-Deriva...           HK.HAI2112
HK.MPImain
['HK.MPImain', 'HK.HAImain']
```

:::tip Interface Limitations
* A maximum of 30 requests for obtaining futures contract data interface every 30 seconds
* The maximum number of futures is 200, in the code list for each request.
:::

---

# Filter Stocks by Condition

`get_stock_filter(market, filter_list, plate_code=None, begin=0, num=200)`

* **Description**

    Filter stocks by condition

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market identifier.  (Does not distinguish between Shanghai and Shenzhen market, either of Shanghai or Shenzhen market will return the Shanghai and Shenzhen markets.)
    filter_list|list|The list of filter conditions.  (Data type of elements in the list is *SimpleFilter*, *AccumulateFilter* or *FinancialFilter*, refer to the following tables.)
    plate_code|str|Plate code.
    begin|int|Data starting point.
    num|int|The number of requested data.
    * The relevant parameters of the *SimpleFilter* object are as follows:

        Field|Type|Description
        :-|:-|:-
        stock_field|[StockField](./quote.md#9377)|Simple filter properties.
        filter_min|float|The lower limit of the interval (closed interval).  (Default by -∞.)
        filter_max|float|The upper limit of the interval (closed interval).  (Default by +∞.)
        is_no_filter|bool|Whether the field does not require filtering.  (True: no filtering. False: filtering. No filtering by default.)
        sort|[SortDir](./quote.md#9029)|Sort direction.  (No sorting by default.)

    * The relevant parameters of the *AccumulateFilter* object are as follows:

        Field|Type|Description
        :-|:-|:-
        stock_field|[StockField](./quote.md#8316)|Cumulative filter properties.
        filter_min|float|The lower limit of the interval (closed interval).  (Default by -∞.)
        filter_max|float|The upper limit of the interval (closed interval).  (Default by +∞.)
        is_no_filter|bool|Whether the field does not require filtering.  (True: no filtering. False: filtering. No filtering by default.)
        sort|[SortDir](./quote.md#9029)|Sort direction.  (No sorting by default.)
        days|int|Accumulative days of filtering data.

    * The relevant parameters of the *FinancialFilter* object are as follows:

        Field|Type|Description
        :-|:-|:-
        stock_field|[StockField](./quote.md#2317)|Financial filter properties.
        filter_min|float|The lower limit of the interval (closed interval).  (Default by -∞.)
        filter_max|float|The upper limit of the interval (closed interval).  (Default by +∞.)
        is_no_filter|bool|Whether the field does not require filtering.  (True: no filtering. False: filtering. No filtering by default.)
        sort|[SortDir](./quote.md#9029)|Sort direction.  (No sorting by default.)
        quarter|[FinancialQuarter](./quote.md#8409)|Accumulation time of financial report.

    * The relevant parameters of the *CustomIndicatorFilter* object are as follows:

        Field|Type|Description
        :-|:-|:-
        stock_field1|[StockField](./quote.md#3936)|Custom indicator filter properties.
        stock_field1_para|list|Custom indicator parameter.  (Pass parameters according to the indicator type:1. MA：[Average moving period] 2.EMA：[Exponential moving average period] 3.RSI：[RSI period] 4.MACD：[Fast average, Slow average, DIF value] 5.BOLL：[Average period, Offset value] 6.KDJ：[RSV period, K value period, D value period]) 
        relative_position|[RelativePosition](./quote.md#9084)|Relative position.
        stock_field2|[StockField](./quote.md#3936)|Custom indicator filter properties.
        stock_field2_para|list|Custom indicator parameter.  (Pass parameters according to the indicator type:1. MA：[Average moving period] 2.EMA：[Exponential moving average period] 3.RSI：[RSI period] 4.MACD：[Fast average, Slow average, DIF value] 5.BOLL：[Average period, Offset value] 6.KDJ：[RSV period, K value period, D value period]) 
        value|float|Custom value.  (When stock_field2 selects 'VALUE' in [StockField](../quote/quote.html#3936), value is a mandatory parameter) 
        ktype|[KLType](./quote.md#66)|K line type KLType (only supports K_60M, K_DAY, K_WEEK, K_MON four time periods).
        consecutive_period|int|Filters data whose consecutive periods are all eligible.  (Fill in the range [1,12].) 
        is_no_filter|bool|Whether the field does not require filtering. True: no filtering, False: filtering. No filtering by default.
 
    * The relevant parameters of the *PatternFilter* object are as follows:

        Field|Type|Description
        :-|:-|:-
        stock_field|[StockField](./quote.md#6605)|Pattern filter properties.
        ktype|[KLType](./quote.md#66)|K line type KLType (only supports K_60M, K_DAY, K_WEEK, K_MON four time periods).
        consecutive_period|int|Filters data whose consecutive periods are all eligible.  (Fill in the range [1,12].) 
        is_no_filter|bool|Whether the field does not require filtering. True: no filtering, False: filtering. No filtering by default.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, stock selection data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Stock selection data format as follows: 
        Field|Type|Description
        :-|:-|:-
        last_page|bool|Is it the last page.
        all_count|int|Total number of lists.
        stock_list|list|Stock selection data.  (Data type of elements in the list is *FilterStockData*.)
       
        - *FilterStockData*'s data format as follows: 

            Field|Type|Description
            :-|:-|:-
            stock_code|str|Stock code.
            stock_name|str|Stock name.
            cur_price|float|Current price.
            cur_price_to_highest_52weeks_ratio|float|(Current price - high in 52 weeks)/high in 52 weeks.  (This field is in percentage form, so 20 is equivalent to 20%.)
            cur_price_to_lowest_52weeks_ratio|float|(Current price - low in 52 weeks)/low in 52 weeks.  (This field is in percentage form, so 20 is equivalent to 20%.)
            high_price_to_highest_52weeks_ratio|float|(Today's high - high in 52 weeks)/high in 52 weeks.  (This field is in percentage form, so 20 is equivalent to 20%.)
            low_price_to_lowest_52weeks_ratio|float|(Today's low - low in 52 weeks)/low in 52 weeks.  (This field is in percentage form, so 20 is equivalent to 20%.)
            volume_ratio|float|Volume ratio.
            bid_ask_ratio|float|The committee.  (This field is in percentage form, so 20 is equivalent to 20%.)
            lot_price|float|Price per lot.
            market_val|float|Market value.
            pe_annual|float|P/E ratio.
            pe_ttm|float|P/E ratio TTM.
            pb_rate|float|P/B ratio.
            change_rate_5min|float|Price change in five minutes.  (This field is in percentage form, so 20 is equivalent to 20%.)
            change_rate_begin_year|float|Price change of this year.  (This field is in percentage form, so 20 is equivalent to 20%.)
            ps_ttm|float|P/S rate TTM.  (This field is in percentage form, so 20 is equivalent to 20%.)
            pcf_ttm|float|P/CF rate TTM.  (This field is in percentage form, so 20 is equivalent to 20%.)
            total_share|float|Total number of shares.  (unit: share)
            float_share|float|Shares outstanding.  (unit: share)
            float_market_val|float|Market capitalization.  (unit: yuan)
            change_rate|float|Price change rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            amplitude|float|Amplitude.  (This field is in percentage form, so 20 is equivalent to 20%.)
            volume|float|Average daily volume.
            turnover|float|Average daily turnover.
            turnover_rate|float|Turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            net_profit|float|Net profit.
            net_profix_growth|float|Net profit growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            sum_of_business|float|Operating income.
            sum_of_business_growth|float|Year-on-year growth rate of operating income.  (This field is in percentage form, so 20 is equivalent to 20%.)
            net_profit_rate|float|Net interest rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            gross_profit_rate|float|Gross profit rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            debt_asset_rate|float|Asset-liability ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            return_on_equity_rate|float|Return on net assets.  (This field is in percentage form, so 20 is equivalent to 20%.)
            roic|float|Return on invested capital.  (This field is in percentage form, so 20 is equivalent to 20%.)
            roa_ttm|float|Return on Assets TTM.  (This field is in percentage form, so 20 is equivalent to 20%.)
            ebit_ttm|float|Earnings before interest and tax TTM.  (unit: yuan. Only applicable to annual reports.)
            ebitda|float|Earnings before interest and tax, depreciation and amortization.  (unit: yuan)
            operating_margin_ttm|float|Operating profit margin TTM.  (This field is in percentage form, so 20 is equivalent to 20%.)
            ebit_margin|float|EBIT profit margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
            ebitda_margin|float|EBITDA profit margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
            financial_cost_rate|float|Financial cost rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            operating_profit_ttm|float|Operating profit TTM.  (unit: yuan. Only applicable to annual reports.)
            shareholder_net_profit_ttm|float|Net profit attributable to the parent company.  (unit: yuan. Only applicable to annual reports.)
            net_profit_cash_cover_ttm|float|Proportion of cash income in profit.  (This field is in percentage form, so 20 is equivalent to 20%.Only applicable to annual reports.)
            current_ratio|float|Current ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            quick_ratio|float|Quick ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            current_asset_ratio|float|Current asset ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            current_debt_ratio|float|Current debt ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            equity_multiplier|float|Equity multiplier.
            property_ratio|float|Property ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            cash_and_cash_equivalents|float|Cash and cash equivalents.  (unit: yuan)
            total_asset_turnover|float|Total asset turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            fixed_asset_turnover|float|Fixed asset turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            inventory_turnover|float|Inventory turnover rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            operating_cash_flow_ttm|float|Operating cash flow TTM.  (unit: yuan. Only applicable to annual reports.)
            accounts_receivable|float|Net accounts receivable.  (unit: yuan)
            ebit_growth_rate|float|EBIT year-on-year growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            operating_profit_growth_rate|float|Operating profit year-on-year growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            total_assets_growth_rate|float|Year-on-year growth rate of total assets.  (This field is in percentage form, so 20 is equivalent to 20%.)
            profit_to_shareholders_growth_rate|float|Year-on-year growth rate of net profit attributable to the parent.  (This field is in percentage form, so 20 is equivalent to 20%.)
            profit_before_tax_growth_rate|float|Year-on-year growth rate of total profit.  (This field is in percentage form, so 20 is equivalent to 20%.)
            eps_growth_rate|float|EPS year-on-year growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            roe_growth_rate|float|ROE year-on-year growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            roic_growth_rate|float|ROIC year-on-year growth rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
            nocf_growth_rate|float|Year-on-year growth rate of operating cash flow.  (This field is in percentage form, so 20 is equivalent to 20%.)
            nocf_per_share_growth_rate|float|Year-on-year growth rate of operating cash flow per share.  (This field is in percentage form, so 20 is equivalent to 20%.)
            operating_revenue_cash_cover|float|Operating cash income ratio.  (This field is in percentage form, so 20 is equivalent to 20%.)
            operating_profit_to_total_profit|float|operating profit percentage.  (This field is in percentage form, so 20 is equivalent to 20%.)
            basic_eps|float|Basic earnings per share.  (unit: yuan)
            diluted_eps|float|Diluted earnings per share.  (unit: yuan)
            nocf_per_share|float|Net operating cash flow per share.  (unit: yuan)
            price|float|latest price
            ma|float|Simple moving average  (Returns values based on the MA parameter.)
            ma5|float|5-day simple moving average
            ma10|float|10-day simple moving average
            ma20|float|20-day simple moving average
            ma30|float|30-day simple moving average
            ma60|float|60-day simple moving average
            ma120|float|120-day simple moving average
            ma250|float|250-day simple moving average
            rsi|float|RSI  (Returns values based on the RSI parameter. The default parameter for RSI is 12.)
            ema|float|exponential moving average  (Returns values based on the EMA parameter.) 
            ema5|float|5-day exponential moving average
            ema10|float|10-day exponential moving average
            ema20|float|20-day exponential moving average
            ema30|float|30-day exponential moving average
            ema60|float|60-day exponential moving average
            ema120|float|120日-day exponential moving average
            ema250|float|250日-day exponential moving average
            kdj_k|float| K value of KDJ indicator  (Returns values based on the KDJ parameter. The default parameter for KDJ is [9,3,3].) 
            kdj_d|float| D value of KDJ indicator  (Returns values based on the KDJ parameter. The default parameter for KDJ is [9,3,3].)
            kdj_j|float| J value of KDJ indicator  (Returns values based on the KDJ parameter. The default parameter for KDJ is [9,3,3].)
            macd_diff|float|DIFF value of MACD indicator  (Returns values based on the MACD parameter. The default parameter for MACD is [12,26,9].) 
            macd_dea|float|DEA value of MACD indicator (Returns values based on the MACD parameter. The default parameter for MACD is [12,26,9].) 
            macd|float|MACD value of MACD indicator  (Returns values based on the MACD parameter. The default parameter for MACD is [12,26,9].) 
            boll_upper|float|UPPER value of BOLL indicator  (Returns values based on the BOLL parameter. The default parameter for BOLL is [20.2].) 
            boll_middler|float|MIDDLER value of BOLL indicator  (Returns values based on the BOLL parameter. The default parameter for BOLL is [20.2].) 
            boll_lower|float|LOWER value of BOLL indicator  (Returns values based on the BOLL parameter. The default parameter for BOLL is [20.2].) 

* **Example**

```python
from moomoo import *
import time

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
simple_filter = SimpleFilter()
simple_filter.filter_min = 2
simple_filter.filter_max = 1000
simple_filter.stock_field = StockField.CUR_PRICE
simple_filter.is_no_filter = False
# simple_filter.sort = SortDir.ASCEND

financial_filter = FinancialFilter()
financial_filter.filter_min = 0.5
financial_filter.filter_max = 50
financial_filter.stock_field = StockField.CURRENT_RATIO
financial_filter.is_no_filter = False
financial_filter.sort = SortDir.ASCEND
financial_filter.quarter = FinancialQuarter.ANNUAL

custom_filter = CustomIndicatorFilter()
custom_filter.ktype = KLType.K_DAY
custom_filter.stock_field1 = StockField.KDJ_K
custom_filter.stock_field1_para = [10,4,4]
custom_filter.stock_field2 = StockField.KDJ_K
custom_filter.stock_field2_para = [9,3,3]
custom_filter.relative_position = RelativePosition.MORE
custom_filter.is_no_filter = False

nBegin = 0
last_page = False
ret_list = list()
while not last_page:
    nBegin += len(ret_list)
    ret, ls = quote_ctx.get_stock_filter(market=Market.HK, filter_list=[simple_filter, financial_filter, custom_filter], begin=nBegin)  # filter with simple, financial and indicator filter for HK market
    if ret == RET_OK:
        last_page, all_count, ret_list = ls
        print('all count = ', all_count)
        for item in ret_list:
            print(item.stock_code)  # Get the stock code
            print(item.stock_name)  # Get the stock name
            print(item[simple_filter])   # Get the value of the variable corresponding to simple_filter
            print(item[financial_filter])   # Get the value of the variable corresponding to financial_filter 
            print(item[custom_filter])  # Get the value of custom_filter
    else:
        print('error: ', ls)
        break
    time.sleep(3)  # Sleep for 3 seconds to avoid trigger frequency limitation

quote_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
39 39 [ stock_code:HK.08103  stock_name:hmvod Limited  cur_price:2.69  current_ratio(annual):4.413 ,  stock_code:HK.00376  stock_name:Yunfeng Financial  cur_price:2.96  current_ratio(annual):12.585 ,  stock_code:HK.09995  stock_name:RemeGen Co., Ltd.  cur_price:92.85  current_ratio(annual):16.054 ,  stock_code:HK.80737  stock_name:Shenzhen Investment Holdings Bay Area Development  cur_price:2.8  current_ratio(annual):17.249 ,  stock_code:HK.00737  stock_name:Shenzhen Investment Holdings Bay Area Development  cur_price:3.25  current_ratio(annual):17.249 ,  stock_code:HK.03939  stock_name:Wanguo International Mining  cur_price:2.22  current_ratio(annual):17.323 ,  stock_code:HK.01055  stock_name:China Southern Airlines  cur_price:5.17  current_ratio(annual):17.529 ,  stock_code:HK.02638  stock_name:HK Electric Investments and HK Electric Investments  cur_price:7.68  current_ratio(annual):21.255 ,  stock_code:HK.00670  stock_name:China Eastern Airlines Corporation  cur_price:3.53  current_ratio(annual):25.194 ,  stock_code:HK.01952  stock_name:Everest Medicines  cur_price:69.5  current_ratio(annual):26.029 ,  stock_code:HK.00089  stock_name:Tai Sang Land Development  cur_price:4.22  current_ratio(annual):26.914 ,  stock_code:HK.00728  stock_name:China Telecom Corporation  cur_price:2.84  current_ratio(annual):27.651 ,  stock_code:HK.01372  stock_name:Bisu Technology Group  cur_price:5.63  current_ratio(annual):28.303 ,  stock_code:HK.00753  stock_name:Air China Limited  cur_price:6.37  current_ratio(annual):31.828 ,  stock_code:HK.01997  stock_name:Wharf Real Estate Investment  cur_price:44.15  current_ratio(annual):33.239 ,  stock_code:HK.02158  stock_name:Yidu Tech Inc.  cur_price:38.95  current_ratio(annual):34.046 ,  stock_code:HK.02588  stock_name:BOC Aviation Ltd.  cur_price:76.85  current_ratio(annual):34.531 ,  stock_code:HK.01330  stock_name:Dynagreen Environmental Protection Group  cur_price:3.36  current_ratio(annual):35.028 ,  stock_code:HK.01525  stock_name:SHANGHAI GENCH EDUCATION GROUP LIMITED  cur_price:6.28  current_ratio(annual):36.989 ,  stock_code:HK.09908  stock_name:JiaXing Gas Group  cur_price:10.02  current_ratio(annual):37.848 ,  stock_code:HK.06078  stock_name:Hygeia Healthcare Holdings  cur_price:49.2  current_ratio(annual):39.0 ,  stock_code:HK.01071  stock_name:Huadian Power International Corporation  cur_price:2.16  current_ratio(annual):39.507 ,  stock_code:HK.00357  stock_name:Hainan Meilan International Airport  cur_price:33.65  current_ratio(annual):39.514 ,  stock_code:HK.00762  stock_name:China Unicom  cur_price:5.21  current_ratio(annual):40.74 ,  stock_code:HK.01787  stock_name:Shandong Gold Mining  cur_price:15.62  current_ratio(annual):41.604 ,  stock_code:HK.00902  stock_name:Huaneng Power International,Inc.  cur_price:2.67  current_ratio(annual):42.919 ,  stock_code:HK.00934  stock_name:Sinopec Kantons  cur_price:2.98  current_ratio(annual):43.361 ,  stock_code:HK.01117  stock_name:China Modern Dairy  cur_price:2.29  current_ratio(annual):45.037 ,  stock_code:HK.00177  stock_name:Jiangsu Expressway  cur_price:8.78  current_ratio(annual):45.93 ,  stock_code:HK.01379  stock_name:Wenling Zhejiang Measuring and Cutting Tools Trading Centre Company Limited*  cur_price:5.71  current_ratio(annual):46.774 ,  stock_code:HK.01876  stock_name:Budweiser Brewing Company APAC Limited  cur_price:22.45  current_ratio(annual):46.917 ,  stock_code:HK.01907  stock_name:China Risun  cur_price:4.38  current_ratio(annual):47.129 ,  stock_code:HK.02160  stock_name:MicroPort CardioFlow Medtech Corporation  cur_price:15.52  current_ratio(annual):47.384 ,  stock_code:HK.00293  stock_name:Cathay Pacific Airways  cur_price:7.13  current_ratio(annual):47.983 ,  stock_code:HK.00694  stock_name:Beijing Capital International Airport  cur_price:6.29  current_ratio(annual):47.985 ,  stock_code:HK.09922  stock_name:Jiumaojiu International Holdings Limited  cur_price:26.8  current_ratio(annual):48.278 ,  stock_code:HK.01083  stock_name:Towngas China  cur_price:3.38  current_ratio(annual):49.2 ,  stock_code:HK.00291  stock_name:China Resources Beer  cur_price:58.2  current_ratio(annual):49.229 ,  stock_code:HK.00306  stock_name:Kwoon Chung Bus  cur_price:2.29  current_ratio(annual):49.769 ]
HK.08103
hmvod Limited
2.69
2.69
4.413
...
HK.00306
Kwoon Chung Bus
2.29
2.29
49.769
```

:::tip Tips
* Use [Get sub-plate list function](../quote/get-plate-list.md) to get the sub-plate code, the plates supported by conditional stock selection are respectively
    1. The industry plate and concept plate of HK market.
    2. Industry plate of US market.
    3. Shanghai and Shenzhen's industry plate, conceptual plate and geographic plate.
* Supported plate index codes
    Code|Description
    :-|:-
    HK.Motherboard|Main plate of HK market
    HK.GEM|Growth Enterprise Market of HK market
    HK.BK1911|Main plate of H-Share
    HK.BK1912|Growth Enterprise Market of H-share
    US.NYSE|New York Stock Exchange
    US.AMEX|American Exchange
    US.NASDAQ|NASDAQ
    SH.3000000|Shanghai main plate
    SZ.3000001|Shenzhen main plate
    SZ.3000004|Shenzhen Growth Enterprise Market
:::

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* At most 200 filter results are returned per page
* It is recommended that the filter conditions do not exceed 250, otherwise "business processing timeout did not return" may appear
* The maximum number of the same filter condition for cumulative filter properties is 10
* If you use dynamic data such as "current price" as the sorting field, the sorting of the data may change between multiple pages
* Non-similar indicators do not support comparison, and are limited to the establishment of comparison relationships between similar indicators, and comparisons across different types of indicators will cause errors. For example: MA5 and MA10 can establish a relationship. MA5 and EMA10 cannot establish a relationship.
* The same type of filter conditions of the custom indicator attribute exceeds the upper limit of 10
* Simple attributes, financial attributes, and morphological attributes do not support repeated designation of filter conditions for the same field
* Stock filter function currently does not support irregular trading hours (i.e.pre-market, post-market and overnight). All results are based on regular trading hours data.
:::

---

# Stock Screening V2

`get_stock_screen(request)`

* **Description**

    Stock screening V2. Compared with the legacy [get_stock_filter](./get-stock-filter.md), this API covers a wider range of factors (11 categories, 244+ factors), accepts raw values for all numeric inputs (OpenD performs magnification conversion automatically), supports single-field or multi-field sorting, requires explicit declaration of retrieve fields, and returns each result through `sval` / `ival` / `aval` / `dval` according to its `value_type`.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    request|StockScreenRequest|Stock screening request object, built via builder methods

    * StockScreenRequest fields:

        Field|Type|Description
        :-|:-|:-
        page_from|int|Pagination start position  (Defaults to 0)
        page_count|int|Maximum results per page  (Defaults to 200)

    * Filter builder methods (each call appends one filter condition; all numeric fields accept raw values, OpenD performs magnification automatically):

        Method|Description
        :-|:-
        add_simple_field(field, values)|Filter by enum field such as market / exchange / index / watchlist  (field comes from [SimpleField](./quote.md#1036); values is a list of enum values (OR-joined). ScrMarket.MY / JP / SG will be supported later; currently the result is empty)
        add_plate(plate_ids, parent_plate_id=None)|Plate filter  (plate_ids like ["BK1001"])
        add_simple_property(name, lower=None, upper=None)|Simple property interval filter  (name comes from [SimpleProperty](./quote.md#3458) (price, market cap, PE, volume ratio, etc.); lower / upper are raw values, e.g. price 10 → 10, market cap ≥ 10B → 10_000_000_000)
        add_cumulative_property(name, days=1, lower=None, upper=None)|Cumulative property  (name comes from [CumulativeProperty](./quote.md#7431); days is the cumulative window. Percent-style fields (e.g. PRICE_CHANGE_PCT) take a **decimal** value (5% as 0.05, NOT 5.0))
        add_financial_property(name, term=None, year=None, lower=None, upper=None, ...)|Financial property  (name comes from [FinancialProperty](./quote.md#9745); term comes from the Term enum (Q1=1, Annual=100, latest single quarter=10, etc.). The Term.SURPRISE_LATEST series (200~204) returns values for both HK and US in practice, but the data is typically identical to ANNUAL — use with caution)
        add_indicator_positional(first_indicator_name, period_type, position, second_indicator=None, ...)|Indicator position relation  (e.g. MA5 crosses above MA20. Indicator/Period/Position come from [Indicator / Period / Position](./quote.md#823))
        add_indicator_pattern(name, period_type, ...)|Indicator pattern (gold cross, dead cross, divergence, etc.)  (name comes from [Pattern](./quote.md#823))
        add_featured_property(name, intervals=None, value_set=None, period=None, range_period=None, first_custom_param=None)|Featured indicator (chip, hotness, analyst rating, capital flow, etc.)
        add_broker_holdings(name, days=None, param=None, intervals=None)|Broker holding factor  (HK only. Supported: 6101 concentration / 6103 count / 6106 CCASS holding ratio / 6107 CCASS holding change. NOT supported: 6102 broker holding change, 6104 broker rank, 6105 broker holding ratio. 6101 / 6106 / 6107 use a multiplier of 1000, pass percentages (e.g. 20% → 20); 6103 has no multiplier (integer). intervals is a dict list keyed by `filterMin` / `filterMax`. The `days` parameter has no effect)
        add_kline_shape(name, period=None, value_set=None)|K-line shape (double bottom, head & shoulders, etc.)  (period is required; only daily K (11) and 1-hour K (21) are supported)
        add_option(name, intervals=None, param=None, period=None)|Option indicator (underlying IV, HV, etc.)

    * Retrieve builder methods (declare which fields to return; if not declared, only stock_id is returned):

        Method|Description
        :-|:-
        add_retrieve_basic(name)|Code / name / industry  (name comes from [BasicProperty](./quote.md#55): CODE=1101, NAME=1102, INDUSTRY=1103)
        add_retrieve_simple(name)|Simple property  (name comes from [SimpleProperty](./quote.md#3458))
        add_retrieve_cumulative(name, days=1, period_average=None)|Cumulative property  (name comes from [CumulativeProperty](./quote.md#7431))
        add_retrieve_financial(name, term=None, year=None, ...)|Financial property  (name comes from [FinancialProperty](./quote.md#9745))
        add_retrieve_indicator(name, period=None, indicator_params=None)|Indicator
        add_retrieve_featured(name, period=None, range_period=None, first_custom_param=None)|Featured property
        add_retrieve_broker(name, days=None, param=None)|Broker
        add_retrieve_option(name, param=None, period=None)|Option property
        add_retrieve_kline_shape(name, period=None)|K-line shape  (period is required, otherwise no result is returned; only daily K (11) and 1-hour K (21) are supported)

    * Sort builder methods:

        Method|Description
        :-|:-
        set_sort(direction, property_type, property_params)|Single-field sort  (direction comes from ScrSortDir: ASC=1, DESC=2, ABS_ASC=3, ABS_DESC=4. property_type is one of 'basic' / 'simple' / 'cumulative' / 'financial' / 'indicator' / 'featured' / 'broker' / 'option' / 'kline_shape')
        add_sort(direction, property_type, property_params)|Multi-field sort  (Applied in call order; mutually exclusive with set_sort, sortList wins when non-empty)

* **Returns**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467">RET_CODE</a></td>
            <td>API result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>When ret == RET_OK, returns (last_page, all_count, items)</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, an error description is returned</td>
        </tr>
    </table>

    * Returned tuple fields:

        Field|Type|Description
        :-|:-|:-
        last_page|bool|Whether this is the last page
        all_count|int|Total number of records matching the conditions
        items|list[dict]|Result list for the current page; each element has the structure `{'stock_id': int, 'results': [result, ...]}`

    * Single result structure:

        Field|Type|Description
        :-|:-|:-
        type|str|Property type  ('basic' / 'simple' / 'cumulative' / 'financial' / 'indicator' / 'featured' / 'broker' / 'option' / 'kline_shape')
        property|dict|Corresponding property descriptor (contains name / days / term, etc.)
        value_type|int|Value type  (1=string(sval), 2=int64(ival), 3=int64 array(aval), 4=double(dval). When OpenD has no data, only value_type is sent (typically 2) and sval/ival/aval/dval are all absent, e.g. HK Q2/Q3/Q4 financial data)
        sval|str|String value (present when value_type=1)
        ival|int|Integer value (present when value_type=2)
        aval|list[int]|Integer array value (present when value_type=3)
        dval|float|Floating-point value (present when value_type=4)
        enum_type_name|str|When ival is an enum code, the corresponding enum type name (e.g. 'KlineShapeType')
        enum_name|str|When ival is an enum code, the decoded enum name returned by OpenD/SDK (e.g. 'DOUBLE_BOTTOMS', 'NONE')
        end_time|int|Financial report end timestamp  (Only for financial type. Current OpenD versions do not populate this field — typically absent from actual results)

* **Example**

```python
from moomoo import OpenQuoteContext, RET_OK, StockScreenRequest
from moomoo.quote.stock_screen_const import (
    ScrMarket, ScrSortDir, SimpleField, SimpleProperty,
    CumulativeProperty, FinancialProperty, Term,
    Indicator, Period, Position, Pattern,
    BasicProperty, KlineShapeProperty, KlineShapeType,
)

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# Example 1: HK large-cap stocks + MACD golden cross
req = StockScreenRequest()
req.add_simple_field(field=SimpleField.MARKET, values=[ScrMarket.HK])
req.add_simple_property(name=SimpleProperty.PRICE, lower=10.0)                   # Last price >= 10
req.add_simple_property(name=SimpleProperty.MARKET_CAP, lower=10_000_000_000.0)  # Market cap >= 10 billion
req.add_simple_property(name=SimpleProperty.PE_TTM, lower=10.0, upper=50.0)      # PE(TTM) 10~50
req.add_indicator_pattern(name=Pattern.MACD_GOLD_CROSS, period_type=Period.DAY)  # MACD golden cross
# Retrieve fields
req.add_retrieve_basic(name=BasicProperty.CODE)
req.add_retrieve_basic(name=BasicProperty.NAME)
req.add_retrieve_simple(name=SimpleProperty.PRICE)
req.add_retrieve_simple(name=SimpleProperty.MARKET_CAP)
req.add_retrieve_simple(name=SimpleProperty.PE_TTM)
# Sort
req.set_sort(direction=ScrSortDir.DESC, property_type='simple',
             property_params={'name': int(SimpleProperty.MARKET_CAP)})
req.page_count = 50

ret, data = quote_ctx.get_stock_screen(req)
if ret == RET_OK:
    last_page, all_count, items = data
    print(f"Total {all_count}, returned {len(items)} this page")
    for it in items[:3]:
        print(it['stock_id'], it['results'])
else:
    print('error: ', data)

# Example 2: Financial factor + cumulative change ratio
req = StockScreenRequest()
req.add_simple_field(field=SimpleField.MARKET, values=[ScrMarket.HK])
req.add_cumulative_property(name=CumulativeProperty.PRICE_CHANGE_PCT,
                            days=5, lower=-0.05, upper=0.05)                     # 5-day change ratio -5%~5% (decimal)
req.add_financial_property(name=FinancialProperty.NET_PROFIT,
                           term=Term.ANNUAL, lower=0.0)                          # Annual net profit > 0
req.add_retrieve_basic(name=BasicProperty.CODE)
req.add_retrieve_simple(name=SimpleProperty.PRICE)
req.page_count = 200
ret, data = quote_ctx.get_stock_screen(req)

# Example 3: K-line shape (double bottom + head-and-shoulders bottom)
req = StockScreenRequest()
req.add_simple_field(field=SimpleField.MARKET, values=[ScrMarket.HK])
req.add_kline_shape(name=KlineShapeProperty.SHAPE_TYPE, period=Period.DAY,
                    value_set=[KlineShapeType.DOUBLE_BOTTOMS,
                               KlineShapeType.HEAD_SHOULDERS_BOTTOM])
req.add_retrieve_basic(name=BasicProperty.CODE)
req.add_retrieve_kline_shape(name=KlineShapeProperty.SHAPE_TYPE, period=Period.DAY)
ret, data = quote_ctx.get_stock_screen(req)

quote_ctx.close()
```

* **Output**

```python
Total 1, returned 1
54047868453564 [{'type': 'basic', 'property': {'name': 1101}, 'value_type': 1, 'sval': '00700'},
                {'type': 'basic', 'property': {'name': 1102}, 'value_type': 1, 'sval': 'Tencent Holdings'},
                {'type': 'simple', 'property': {'name': 2201}, 'value_type': 4, 'dval': 460.0},
                {'type': 'simple', 'property': {'name': 2301}, 'value_type': 4, 'dval': 4194280264040.0},
                {'type': 'simple', 'property': {'name': 2303}, 'value_type': 4, 'dval': 15.75126}]
```

* **Per-field examples (by category)**

    > All examples below target the HK market: first `req = StockScreenRequest()`, then `req.add_simple_field(field=SimpleField.MARKET, values=[ScrMarket.HK])`,
    > stack the filter / retrieve / sort conditions from each section, and finally `quote_ctx.get_stock_screen(req)` to obtain `(last_page, all_count, items)`.
    > The measured `head` expands the corresponding property values inside the `results` array (code/name come from BasicProperty.CODE/NAME; factor column names are the lower-cased SDK field names).

    #### Simple market property (SimpleProperty)

    Passed via `add_simple_property(name, lower, upper)`. `lower/upper` take the raw value (currency/shares/percentage 5% as 5.0)

    ##### `PRICE`（id=2201 · simple · SimpleProperty） Latest price

    Unit: in currency; lower/upper take the raw price, OpenD applies the multiplier automatically

    ```python
    req.add_simple_property(name=SimpleProperty.PRICE, lower=10.0)
    req.add_retrieve_simple(name=SimpleProperty.PRICE)
    req.set_sort(direction=ScrSortDir.DESC, property_type='simple',
                 property_params={'name': int(SimpleProperty.PRICE)})
    ```

    Measured response (HK · all_count=485, 5 rows matched, head top 5):

    ```
          stock_id   code    name   price
    47704201761008  04336  应用材料-T  1620.0
    87836376173009  02513      智谱  1097.0
    47704201761005  04333    思科-T   750.0
    86839943761574  03750    宁德时代   672.5
    87840671141778  03986    兆易创新   653.5
    ```

    ##### `MARKET_CAP`（id=2301 · simple · SimpleProperty） Market cap

    Unit: in currency; lower=10 billion as 10_000_000_000

    ```python
    req.add_simple_property(name=SimpleProperty.MARKET_CAP, lower=10_000_000_000.0)
    req.add_retrieve_simple(name=SimpleProperty.MARKET_CAP)
    req.set_sort(direction=ScrSortDir.DESC, property_type='simple',
                 property_params={'name': int(SimpleProperty.MARKET_CAP)})
    ```

    Measured response (HK · all_count=591, 5 rows matched, head top 5):

    ```
          stock_id   code    name        market_cap
    54047868453564  00700    腾讯控股   4222484299075.2
    83820581829436  80700  腾讯控股-R   3641391766113.6
    86839943761574  03750    宁德时代   3111406771825.0
    47704201761005  04333    思科-T   2956075998750.0
    57754425230710  01398    工商银行  2573253176182.58
    ```

    ##### `PE_TTM`（id=2303 · simple · SimpleProperty） PE(TTM)

    Standard range filter; negative values allowed

    ```python
    req.add_simple_property(name=SimpleProperty.PE_TTM, lower=5.0, upper=20.0)
    req.add_retrieve_simple(name=SimpleProperty.PE_TTM)
    req.set_sort(direction=ScrSortDir.ASC, property_type='simple',
                 property_params={'name': int(SimpleProperty.PE_TTM)})
    ```

    Measured response (HK · all_count=830, 5 rows matched, head top 5):

    ```
          stock_id   code      name  pe_ttm
    28604482191640  00280      景福集团     5.0
    67345087202619  01339  中国人民保险集团   5.037
    68629282424057  01273      香港信贷  5.0847
    76063870813891  01731    其利工业集团  5.0877
    35433480192608  00608      达利国际  5.0877
    ```

    ##### `VOLUME_RATIO`（id=2217 · simple · SimpleProperty） Volume ratio

    Today volume / N-day average volume; > 2 means heavy volume

    ```python
    req.add_simple_property(name=SimpleProperty.VOLUME_RATIO, lower=2.0)
    req.add_retrieve_simple(name=SimpleProperty.VOLUME_RATIO)
    req.set_sort(direction=ScrSortDir.DESC, property_type='simple',
                 property_params={'name': int(SimpleProperty.VOLUME_RATIO)})
    ```

    Measured response (HK · all_count=340, 5 rows matched, head top 5):

    ```
          stock_id   code      name  volume_ratio
    50796578209975  00183      宏辉集团         600.0
    45999099741384  01224      中渝置地       404.642
              1543  01543  中盈盛达融资担保       400.714
    24142011170996  00180      开达集团       314.999
     5033701671181  00269    中国资源交通         200.0
    ```

    ##### `DIVIDEND_RATIO`（id=2305 · simple · SimpleProperty） Dividend yield

    Unit: %; dividend yield ≥ 5% as 5.0

    ```python
    req.add_simple_property(name=SimpleProperty.DIVIDEND_RATIO, lower=5.0)
    req.add_retrieve_simple(name=SimpleProperty.DIVIDEND_RATIO)
    req.set_sort(direction=ScrSortDir.DESC, property_type='simple',
                 property_params={'name': int(SimpleProperty.DIVIDEND_RATIO)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No HK sample currently has dividend yield ≥ 5%; can lower the threshold

    #### Cumulative market property (CumulativeProperty)

    Passed via `add_cumulative_property(name, days, lower, upper)`. **Percentage values (change %, turnover %) are decimals** (5% as 0.05)

    ##### `PRICE_CHANGE_PCT`（id=3102 · cumulative · CumulativeProperty） N-day price change %

    **Percentage as decimal**: 5% as 0.05; `days` is the N-day cumulative window

    ```python
    req.add_cumulative_property(name=CumulativeProperty.PRICE_CHANGE_PCT,
                                days=5, lower=0.05)
    req.add_retrieve_cumulative(name=CumulativeProperty.PRICE_CHANGE_PCT, days=5)
    req.set_sort(direction=ScrSortDir.DESC, property_type='cumulative',
                 property_params={'name': int(CumulativeProperty.PRICE_CHANGE_PCT), 'days': 5})
    ```

    Measured response (HK · all_count=363, 5 rows matched, head top 5):

    ```
          stock_id   code      name  change_pct_5d
    88510686038921  02953     嬴集团股权            4.0
    77640123811704  01912       康特隆         2.7679
    47704201761005  04333      思科-T         2.2029
    88467736365964  02956  中国健康科技股权         1.6667
    47704201761008  04336    应用材料-T         1.4384
    ```

    ##### `AMPLITUDE`（id=3103 · cumulative · CumulativeProperty） N-day amplitude %

    Same as PRICE_CHANGE_PCT, percentage as decimal

    ```python
    req.add_cumulative_property(name=CumulativeProperty.AMPLITUDE,
                                days=20, lower=0.1)
    req.add_retrieve_cumulative(name=CumulativeProperty.AMPLITUDE, days=20)
    req.set_sort(direction=ScrSortDir.DESC, property_type='cumulative',
                 property_params={'name': int(CumulativeProperty.AMPLITUDE), 'days': 20})
    ```

    Measured response (HK · all_count=2345, 5 rows matched, head top 5):

    ```
          stock_id   code    name  amp_20d
    47704201761008  04336  应用材料-T  43.3783
    55671366092780  02028    映美控股   9.0893
    59558311493749  00117  天利控股集团   8.0532
    42623255446398  00894    万裕科技     7.59
    88433376627363  02723    深演智能   6.3243
    ```

    ##### `AVG_VOLUME`（id=3104 · cumulative · CumulativeProperty） N-day average volume

    Unit: shares; arithmetic mean of N-day volume

    ```python
    req.add_cumulative_property(name=CumulativeProperty.AVG_VOLUME,
                                days=20, lower=1_000_000)
    req.add_retrieve_cumulative(name=CumulativeProperty.AVG_VOLUME, days=20)
    req.set_sort(direction=ScrSortDir.DESC, property_type='cumulative',
                 property_params={'name': int(CumulativeProperty.AVG_VOLUME), 'days': 20})
    ```

    Measured response (HK · all_count=2295, 5 rows matched, head top 5):

    ```
          stock_id   code    name  avg_vol_20d
    84688165145005  02477    经纬天地  15586288027
    58506044508119  02007     碧桂园  11318232417
    69325067126991  02255  海昌海洋公园  10691740000
    81462644703252  00020    商汤-W   9517974535
    79671643350793  09993    金辉控股   7418314265
    ```

    ##### `TURNOVER_RATIO`（id=3106 · cumulative · CumulativeProperty） N-day cumulative turnover %

    Unit: %; percentage as decimal (5% as 0.05)

    ```python
    req.add_cumulative_property(name=CumulativeProperty.TURNOVER_RATIO,
                                days=20, lower=0.05)
    req.add_retrieve_cumulative(name=CumulativeProperty.TURNOVER_RATIO, days=20)
    req.set_sort(direction=ScrSortDir.DESC, property_type='cumulative',
                 property_params={'name': int(CumulativeProperty.TURNOVER_RATIO), 'days': 20})
    ```

    Measured response (HK · all_count=800, 5 rows matched, head top 5):

    ```
          stock_id   code   name  turnover_ratio_20d
    58196806861368  00568   山东墨龙              6.7527
    84688165145005  02477   经纬天地              3.8966
    88089779243675  02715    埃斯顿              3.7288
    84434762074537  02473  喜相逢集团              3.4646
    87230785784391  02631   天岳先进              3.2208
    ```

    #### Financial property (FinancialProperty)

    Passed via `add_financial_property(name, term, year, lower, upper)`. `term` comes from the `Term` enum (Annual=100, Q1=1; TTM does not need term); **ratios are decimals** (15% as 0.15)

    ##### `NET_PROFIT`（id=4101 · financial · FinancialProperty） Net profit

    Unit: in currency; term=ANNUAL(100) for annual, Q1=1, Q2/Q3/Q4 for partial periods

    ```python
    req.add_financial_property(name=FinancialProperty.NET_PROFIT,
                               term=Term.ANNUAL, lower=1_000_000_000.0)
    req.add_retrieve_financial(name=FinancialProperty.NET_PROFIT, term=Term.ANNUAL)
    req.set_sort(direction=ScrSortDir.DESC, property_type='financial',
                 property_params={'name': int(FinancialProperty.NET_PROFIT),
                                  'term': int(Term.ANNUAL)})
    ```

    Measured response (HK · all_count=437, 5 rows matched, head top 5):

    ```
          stock_id   code    name      net_profit
    57754425230710  01398    工商银行  412328868600.0
    56186762167211  00939    建设银行  377880459000.0
    63586990818568  01288    农业银行  324736536300.0
    57118770073492  03988    中国银行  286850625600.0
    83820581829436  80700  腾讯控股-R  255561692100.0
    ```

    ##### `ROE`（id=4110 · financial · FinancialProperty） Return on equity

    Unit: %; percentage as decimal (15% as 0.15); term=ANNUAL

    ```python
    req.add_financial_property(name=FinancialProperty.ROE,
                               term=Term.ANNUAL, lower=0.15)
    req.add_retrieve_financial(name=FinancialProperty.ROE, term=Term.ANNUAL)
    req.set_sort(direction=ScrSortDir.DESC, property_type='financial',
                 property_params={'name': int(FinancialProperty.ROE),
                                  'term': int(Term.ANNUAL)})
    ```

    Measured response (HK · all_count=322, 5 rows matched, head top 5):

    ```
          stock_id   code    name      roe
    62487479191132  01628    禹洲集团   40.644
    69823283339309  08237    华星控股  12.6906
    52845277610549  00565  锦艺集团控股   3.0644
    86882893433405  02621    手回集团   2.7027
    64969970288874  02282   美高梅中国   2.6886
    ```

    ##### `REVENUE_GROWTH`（id=4106 · financial · FinancialProperty） Revenue YoY growth

    Unit: %; percentage as decimal (20% as 0.20); term=ANNUAL

    ```python
    req.add_financial_property(name=FinancialProperty.REVENUE_GROWTH,
                               term=Term.ANNUAL, lower=0.20)
    req.add_retrieve_financial(name=FinancialProperty.REVENUE_GROWTH, term=Term.ANNUAL)
    req.set_sort(direction=ScrSortDir.DESC, property_type='financial',
                 property_params={'name': int(FinancialProperty.REVENUE_GROWTH),
                                  'term': int(Term.ANNUAL)})
    ```

    Measured response (HK · all_count=638, 5 rows matched, head top 5):

    ```
          stock_id   code    name  revenue_growth
    46772193854353  00913    港湾数字        106.7922
    88377542057458  07666  剂泰科技-P          73.067
    53047141075220  02324    首都创投         63.5792
    43589623088228  01124    沿海家园         26.7323
    74259984551169  03329    交银国际         20.5256
    ```

    ##### `BASIC_EPS`（id=4801 · financial · FinancialProperty） Basic EPS

    Unit: in currency; term=ANNUAL

    ```python
    req.add_financial_property(name=FinancialProperty.BASIC_EPS,
                               term=Term.ANNUAL, lower=1.0)
    req.add_retrieve_financial(name=FinancialProperty.BASIC_EPS, term=Term.ANNUAL)
    req.set_sort(direction=ScrSortDir.DESC, property_type='financial',
                 property_params={'name': int(FinancialProperty.BASIC_EPS),
                                  'term': int(Term.ANNUAL)})
    ```

    Measured response (HK · all_count=324, 5 rows matched, head top 5):

    ```
          stock_id   code             name      basic_eps
    86998857554659  06883             颖通控股  123007487.548
    88261577939456  06656             思格新能        139.457
    69290707392656  06288  FAST RETAIL-DRS         74.984
    80418967660265  09961           携程集团-S         56.044
    85439784425509  06181             老铺黄金         31.388
    ```

    ##### `DIVIDENDS_TTM_RATIO`（id=4219 · financial · FinancialProperty） TTM dividend yield

    Unit: %; percentage as decimal; TTM family does not need term/year

    ```python
    req.add_financial_property(name=FinancialProperty.DIVIDENDS_TTM_RATIO, lower=0.05)
    req.add_retrieve_financial(name=FinancialProperty.DIVIDENDS_TTM_RATIO)
    req.set_sort(direction=ScrSortDir.DESC, property_type='financial',
                 property_params={'name': int(FinancialProperty.DIVIDENDS_TTM_RATIO)})
    ```

    Measured response (HK · all_count=463, 5 rows matched, head top 5):

    ```
          stock_id   code    name  div_ttm_ratio
    50856707752105  00169  万达酒店发展         4.0526
              2136  02136    利福中国         0.6562
    77622943942788  02180    万宝盛华         0.3752
    75419625726233  08473  弥明生活百货         0.3303
    64896955845349  02789    远大中国         0.2994
    ```

    #### Technical indicator positional (Indicator)

    Passed via `add_indicator_positional(first_indicator_name, period_type, position, second_indicator=None, value=None, first_indicator_params=None)`. `position` comes from `Position` (OVER=1, BELOW=2, CROSS_UP=3, CROSS_DOWN=4)

    ##### `MA5 / MA20`（id=11 · indicator · Indicator） MA5 crosses above MA20

    add_indicator_positional: first/second are both `Indicator` enum names

    ```python
    req.add_indicator_positional(first_indicator_name=Indicator.MA5,
                                 period_type=Period.DAY,
                                 position=Position.CROSS_UP,
                                 second_indicator=Indicator.MA20)
    ```

    Measured response (HK · all_count=67, 5 rows matched, head top 5):

    ```
          stock_id   code    name
    88356067214548  01236   乐动机器人
    88313117542845  02493  迈威生物-B
    88179973556902  02726    瀚天天成
    87033217287972  01828    富卫集团
    86968792779992  03288    海天味业
    ```

    ##### `RSI`（id=52 · indicator · Indicator） RSI overbought (>70)

    Indicator params via first_indicator_params, e.g. RSI period 14

    ```python
    req.add_indicator_positional(first_indicator_name=Indicator.RSI,
                                 period_type=Period.DAY,
                                 position=Position.OVER, second_value=70,
                                 first_indicator_params=[14])
    ```

    Measured response (HK · all_count=97, 5 rows matched, head top 5):

    ```
          stock_id   code     name
    88502096109937  08561  爱世纪集团股权
    88476326299379  01779   天辰生物-B
    88450556496782  02958  远见控股(旧)
    88416196762328  06872   丹诺医药-B
    88407606823814  02950  升能集团(旧)
    ```

    ##### `MACD_DIF`（id=41 · indicator · Indicator） MACD DIF above zero

    second_value is a single threshold; position=OVER means DIF > value

    ```python
    req.add_indicator_positional(first_indicator_name=Indicator.MACD_DIF,
                                 period_type=Period.DAY,
                                 position=Position.OVER, second_value=0)
    ```

    Measured response (HK · all_count=786, 5 rows matched, head top 5):

    ```
          stock_id   code      name
    88476326299379  01779    天辰生物-B
    88467736365964  02956  中国健康科技股权
    88450556496782  02958   远见控股(旧)
    88437671594888  02952  杭品生活科技股权
    88433376627363  02723      深演智能
    ```

    ##### `PRICE / BOLL_UPPER`（id=1 · indicator · Indicator） Price above BOLL upper

    Compares PRICE(1) with BOLL_UPPER(61) positionally

    ```python
    req.add_indicator_positional(first_indicator_name=Indicator.PRICE,
                                 period_type=Period.DAY,
                                 position=Position.CROSS_UP,
                                 second_indicator=Indicator.BOLL_UPPER)
    ```

    Measured response (HK · all_count=50, 5 rows matched, head top 5):

    ```
          stock_id   code    name
    87544318404244  09876  大洋环球控股
    85864986184208  02576  太美医疗科技
    84482006714840  02520    山西安装
    83000243002163  06963    阳光保险
    82961588291781  02245    力勤资源
    ```

    #### Technical indicator pattern (Pattern)

    Passed via `add_indicator_pattern(name, period_type)`. `name` comes from the `Pattern` enum

    ##### `MACD_GOLD_CROSS`（id=21 · pattern · Pattern） MACD golden cross

    add_indicator_pattern: name comes from the Pattern enum

    ```python
    req.add_indicator_pattern(name=Pattern.MACD_GOLD_CROSS, period_type=Period.DAY)
    ```

    Measured response (HK · all_count=116, 5 rows matched, head top 5):

    ```
          stock_id   code      name
    88502096109937  08561   爱世纪集团股权
    88416196764014  08558  麦迪森控股(旧)
    88265872906147  06051        有赞
    86998857553944  06168       周六福
    86822763895471  06831      绿茶集团
    ```

    ##### `KDJ_GOLD_CROSS`（id=11 · pattern · Pattern） KDJ golden cross

    Same as above, K crosses above D

    ```python
    req.add_indicator_pattern(name=Pattern.KDJ_GOLD_CROSS, period_type=Period.DAY)
    ```

    Measured response (HK · all_count=179, 5 rows matched, head top 5):

    ```
          stock_id   code           name
    88480621267856  02960  ALCO HOLD RTS
    88420491725703  02951        京玖康疗(旧)
    88179973556702  02526           德适-B
    87746181861167  03887  HASHKEY HLDGS
    87741886892639  02655           果下科技
    ```

    ##### `BOLL_BREAK_UPPER`（id=41 · pattern · Pattern） Price breaks BOLL upper

    BOLL pattern series 41~44

    ```python
    req.add_indicator_pattern(name=Pattern.BOLL_BREAK_UPPER, period_type=Period.DAY)
    ```

    Measured response (HK · all_count=50, 5 rows matched, head top 5):

    ```
          stock_id   code    name
    87544318404244  09876  大洋环球控股
    85864986184208  02576  太美医疗科技
    84482006714840  02520    山西安装
    83000243002163  06963    阳光保险
    82961588291781  02245    力勤资源
    ```

    #### Featured property (FeaturedProperty)

    Passed via `add_featured_property(name, intervals, value_set, period, range_period, first_custom_param)`. Use `intervals=[{...}]` for ranges and `value_set=[...]` for enums

    ##### `SHORT_POSITION`（id=5110 · featured · FeaturedProperty） Short position

    Unit: shares; intervals not needed

    ```python
    req.add_featured_property(name=FeaturedProperty.SHORT_POSITION)
    req.add_retrieve_featured(name=FeaturedProperty.SHORT_POSITION)
    req.set_sort(direction=ScrSortDir.DESC, property_type='featured',
                 property_params={'name': int(FeaturedProperty.SHORT_POSITION)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: This featured factor is not exposed for HK; switch to the US market to query

    ##### `ANALYST_RATING`（id=5401 · featured · FeaturedProperty） Analyst rating

    Enum: 1=Strong Buy, 2=Buy, 3=Hold, 4=Sell, 5=Strong Sell; pass value_set array

    ```python
    req.add_featured_property(name=FeaturedProperty.ANALYST_RATING, value_set=[1, 2])
    req.add_retrieve_featured(name=FeaturedProperty.ANALYST_RATING)
    req.set_sort(direction=ScrSortDir.ASC, property_type='featured',
                 property_params={'name': int(FeaturedProperty.ANALYST_RATING)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Switch to the US market with higher coverage, or broaden value_set

    ##### `ANALYST_TARGET_PRICE`（id=5403 · featured · FeaturedProperty） Analyst target price

    Unit: in currency; intervals as dict list `[{'lower': {'value': X, 'includes': True}}]`

    ```python
    req.add_featured_property(name=FeaturedProperty.ANALYST_TARGET_PRICE,
                              intervals=[{'lower': {'value': 100.0, 'includes': True}}])
    req.add_retrieve_featured(name=FeaturedProperty.ANALYST_TARGET_PRICE)
    req.set_sort(direction=ScrSortDir.DESC, property_type='featured',
                 property_params={'name': int(FeaturedProperty.ANALYST_TARGET_PRICE)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Switch to the US market with higher coverage, or relax intervals lower bound

    ##### `HIST_PERCENTILE_PE`（id=5502 · featured · FeaturedProperty） Current PE historical percentile

    range_period required: RangePeriod enum (THREE_MONTHS=1, SIX_MONTHS=2, ONE_YEAR=3, THREE_YEARS=4)

    ```python
    req.add_featured_property(name=FeaturedProperty.HIST_PERCENTILE_PE,
                              range_period=RangePeriod.THREE_YEARS,
                              intervals=[{'upper': {'value': 0.30, 'includes': True}}])
    req.add_retrieve_featured(name=FeaturedProperty.HIST_PERCENTILE_PE,
                              range_period=RangePeriod.THREE_YEARS)
    req.set_sort(direction=ScrSortDir.ASC, property_type='featured',
                 property_params={'name': int(FeaturedProperty.HIST_PERCENTILE_PE),
                                  'rangePeriod': int(RangePeriod.THREE_YEARS)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Some HK stocks lack historical PE; can relax range_period / intervals

    ##### `CASH_FLOW_MAIN_NET_IN`（id=5901 · featured · FeaturedProperty） Main capital net inflow

    Unit: in currency; cash flow uses CashFlowPeriod enum (DAY=1, WEEK=2, MONTH_P=3, QUARTER=4)

    ```python
    req.add_featured_property(name=FeaturedProperty.CASH_FLOW_MAIN_NET_IN,
                              range_period=CashFlowPeriod.DAY,
                              intervals=[{'lower': {'value': 10_000_000.0, 'includes': True}}])
    req.add_retrieve_featured(name=FeaturedProperty.CASH_FLOW_MAIN_NET_IN,
                              range_period=CashFlowPeriod.DAY)
    req.set_sort(direction=ScrSortDir.DESC, property_type='featured',
                 property_params={'name': int(FeaturedProperty.CASH_FLOW_MAIN_NET_IN),
                                  'rangePeriod': int(CashFlowPeriod.DAY)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No data measured on HK; recommend the US market or a shorter period

    #### Broker holdings (BrokerProperty)

    Passed via `add_broker_holdings(name, days, param, intervals)`. **HK only**; the `days` parameter has no effect.

    - **Supported factors**: 6101 concentration / 6103 count / 6106 CCASS holding ratio / 6107 CCASS holding change
    - **Unsupported factors**: 6102 broker holding change, 6104 broker rank, 6105 broker holding ratio
    - **Multiplier**: 6101 / 6106 / 6107 use a multiplier of 1000, pass percentages (20% as 20); 6103 has no multiplier (integer)
    - **`intervals` usage**: dict list keyed by `filterMin` / `filterMax` (**not `lower` / `upper`**), supports one- or two-sided ranges. Examples: `[{'filterMin': {'value': 20.0, 'includes': True}}]` or `[{'filterMin': {'value': 20.0, 'includes': True}, 'filterMax': {'value': 50.0, 'includes': False}}]`

    ##### `CONCENTRATED_DISTRIBUTION`（id=6101 · broker · BrokerProperty） Broker concentration

    HK only; intervals as dict list, unit % (20% as 20.0)

    ```python
    req.add_broker_holdings(name=BrokerProperty.CONCENTRATED_DISTRIBUTION,
                            intervals=[{'filterMin': {'value': 20.0, 'includes': True}}])
    req.add_retrieve_broker(name=BrokerProperty.CONCENTRATED_DISTRIBUTION)
    req.set_sort(direction=ScrSortDir.DESC, property_type='broker',
                 property_params={'name': int(BrokerProperty.CONCENTRATED_DISTRIBUTION)})
    ```

    ##### `CENTRAL_HOLDINGS_RATIO`（id=6106 · broker · BrokerProperty） CCASS holding ratio

    HK only; intervals as dict list, unit %

    ```python
    req.add_broker_holdings(name=BrokerProperty.CENTRAL_HOLDINGS_RATIO,
                            intervals=[{'filterMin': {'value': 10.0, 'includes': True}}])
    req.add_retrieve_broker(name=BrokerProperty.CENTRAL_HOLDINGS_RATIO)
    req.set_sort(direction=ScrSortDir.DESC, property_type='broker',
                 property_params={'name': int(BrokerProperty.CENTRAL_HOLDINGS_RATIO)})
    ```

    ##### `BROKER_NUM`（id=6103 · broker · BrokerProperty） Number of brokers holding the stock

    HK only; integer (intervals as dict list)

    ```python
    req.add_broker_holdings(name=BrokerProperty.BROKER_NUM,
                            intervals=[{'filterMin': {'value': 100, 'includes': True}}])
    req.add_retrieve_broker(name=BrokerProperty.BROKER_NUM)
    req.set_sort(direction=ScrSortDir.DESC, property_type='broker',
                 property_params={'name': int(BrokerProperty.BROKER_NUM)})
    ```

    #### K-line shape (KlineShapeProperty)

    Passed via `add_kline_shape(name, period, value_set)`. `period` is required; currently only daily (`Period.DAY`=11) and 1-hour (`Period.HOUR_1`=5) are supported

    ##### `SHAPE_TYPE`（id=6200 · kline_shape · KlineShapeProperty） K-line shape detection

    period required: daily K=11, 1-hour K=5 (measured discrepancy with SDK doc)

    ```python
    req.add_kline_shape(name=KlineShapeProperty.SHAPE_TYPE, period=Period.DAY,
                        value_set=[KlineShapeType.DOUBLE_BOTTOMS,
                                   KlineShapeType.HEAD_SHOULDERS_BOTTOM])
    req.add_retrieve_kline_shape(name=KlineShapeProperty.SHAPE_TYPE, period=Period.DAY)
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: No match for the specified shape + interval; can broaden value_set

    ##### `RISE_PROB`（id=6201 · kline_shape · KlineShapeProperty） Post-shape rise probability

    Unit: %; used together with SHAPE_TYPE

    ```python
    req.add_kline_shape(name=KlineShapeProperty.SHAPE_TYPE, period=Period.DAY,
                        value_set=[KlineShapeType.DOUBLE_BOTTOMS])
    req.add_retrieve_kline_shape(name=KlineShapeProperty.RISE_PROB, period=Period.DAY)
    req.set_sort(direction=ScrSortDir.DESC, property_type='kline_shape',
                 property_params={'name': int(KlineShapeProperty.RISE_PROB),
                                  'period': int(Period.DAY)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Used together with SHAPE_TYPE; no match in the HK sample

    #### Option property (OptionProperty)

    Passed via `add_option(name, intervals, param, period)`. Used to screen by underlying-stock option dimensions such as IV / HV

    ##### `STOCK_IV`（id=1000 · option · OptionProperty） Underlying option IV

    Unit: %; intervals as dict list; period from OptionHVPeriod enum

    ```python
    req.add_option(name=OptionProperty.STOCK_IV,
                   intervals=[{'lower': {'value': 30.0, 'includes': True}}])
    req.add_retrieve_option(name=OptionProperty.STOCK_IV)
    req.set_sort(direction=ScrSortDir.DESC, property_type='option',
                 property_params={'name': int(OptionProperty.STOCK_IV)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Switch to a market with full option coverage (US) or lower the intervals threshold

    ##### `STOCK_IV_RANK`（id=1001 · option · OptionProperty） Underlying IV rank

    0~100; relative position of current IV in historical range (intervals as dict list)

    ```python
    req.add_option(name=OptionProperty.STOCK_IV_RANK,
                   intervals=[{'lower': {'value': 50.0, 'includes': True}}])
    req.add_retrieve_option(name=OptionProperty.STOCK_IV_RANK)
    req.set_sort(direction=ScrSortDir.DESC, property_type='option',
                 property_params={'name': int(OptionProperty.STOCK_IV_RANK)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Switch to a market with full option coverage (US) or lower the intervals threshold

    ##### `STOCK_HV`（id=1006 · option · OptionProperty） Underlying historical volatility

    Unit: %; intervals as dict list; period from OptionHVPeriod enum

    ```python
    req.add_option(name=OptionProperty.STOCK_HV,
                   intervals=[{'lower': {'value': 20.0, 'includes': True}}])
    req.add_retrieve_option(name=OptionProperty.STOCK_HV)
    req.set_sort(direction=ScrSortDir.DESC, property_type='option',
                 property_params={'name': int(OptionProperty.STOCK_HV)})
    ```

    Measured response (HK · all_count=0, 0 rows matched): no data. Reason: Switch to a market with full option coverage (US) or lower the intervals threshold

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Get the List of Stocks in The Plate

`get_plate_stock(plate_code, sort_field=SortField.CODE, ascend=True)`

* **Description**

    Get the list of stocks in the plate, or get the constituent stocks of the stock index

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    plate_code|str|Plate code.  (You can use [Get plate list](../quote/get-plate-list.md) to get other plates code.For example, "SH.BK0001", "SH.BK0002".)
    sort_field|[SortField](./quote.md#5823)|Sort field.
    ascend|bool|Sort direction.  (True: ascending order. False: descending order.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, stock data of the plate is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Stock data of the plate format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        lot_size|int|The number of shares per lot, or contract multiplier for futures.
        stock_name|str|Stock name.
        stock_type|[SecurityType](./quote.md#9767)|Stock type.
        list_time|str|Time of listing.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        stock_id|int|Stock ID.
        main_contract|bool|Whether future main contract.  (Specific field for futures.)
        last_trade_time|str|Last trading time.  (The field is unique to futures. Main, current month and next month futures do not have this field.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_plate_stock('HK.BK1001')
if ret == RET_OK:
    print(data)
    print(data['stock_name'][0]) # Take the first stock name
    print(data['stock_name'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code  lot_size stock_name  stock_owner  stock_child_type stock_type   list_time        stock_id  main_contract last_trade_time
0   HK.00462      4000       Natural dairy          NaN               NaN      STOCK  2005-06-10  55589761712590          False                
..       ...       ...        ...          ...               ...        ...         ...             ...            ...             ...
9   HK.06186      1000           China Feihe Limited          NaN               NaN      STOCK  2019-11-13  78159814858794          False                

[10 rows x 10 columns]
Natural Dairy
['Natural Dairy', 'China Modern Dairy', 'Yashili International', 'YuanShengTai Dairy Farm', 'China Shengmu Organic Milk', 'China ZhongDi Dairy Holdings', 'Lanzhou Zhuangyuan Pasture', 'Ausnutria Dairy Corporation', 'China Mengniu Dairy', 'China Feihe Limited']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

::: details Commonly used sectors and index codes
Code|Description
:-|:-
HK.HSI Constituent Stocks|HSI constituent stocks
HK.HSCEI Stock|HSCEI constituent stocks
HK.Motherboard|Main Plate of Hong Kong Stocks
HK.GEM|GEM(Growth Enterprise Market) Hong Kong Stocks
HK.LIST1910|All Hong Kong stocks
HK.LIST1911|Main Plate H shares
HK.LIST1912|GEM H shares
HK.Fund|ETF (Hong Kong Stock Fund)
HK.LIST1600|Hot List (Hong Kong)
HK.LIST1921|Listed new shares-Hong Kong stocks
SH.LIST3000000|Shanghai Main Plate
SH.LIST0901|Shanghai Stock Exchange B shares
SH.LIST0902|Shenzhen Stock Exchange B shares
SH.LIST3000002|Shanghai and Shenzhen Index
SH.LIST3000005|All A-shares (Shanghai and Shenzhen)
SH.LIST0600|Hot List (Shanghai and Shenzhen)
SH.LIST0992|Science Innovation Plate
SH.LIST0921|Listed New Shares - A-shares
SZ.LIST3000001|SZSE Main Plate
SZ.LIST3000003|Small and Medium Plate
SZ.LIST3000004|The Growth Enterprise Market (Deep)
US.USAALL|All US stocks
:::

---

# Get Plate List

`get_plate_list(market, plate_class)`

* **Description**

    Obtain a list of stock sectors

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market identification.  (Note: Shanghai and Shenzhen are not distinguished here. Entering Shanghai or Shenzhen will return to the sub-plates of the Shanghai and Shenzhen markets.)
    plate_class|[Plate](./quote.md#978)|Plate classification.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, data of the plate list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Data of the plate list format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Plate code.
        plate_name|str|Plate name.
        plate_id|str|Plate ID.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_plate_list(Market.HK, Plate.CONCEPT)
if ret == RET_OK:
    print(data)
    print(data['plate_name'][0]) # Take the first plate name
    print(data['plate_name'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code plate_name plate_id
0   HK.BK1000      Short Collection   BK1000
..        ...        ...      ...
77  HK.BK1999      Funeral Concept    BK1999

[78 rows x 3 columns]
Short Collection
['Short Collection','Ali concept stocks','Xiongan concept stocks','Apple concept','One Belt One Road', '5G concept','Nightclub stocks','Guangdong-Hong Kong-Macao Greater Bay Area','Tes Pull concept stocks','beer','suspected financial technology stocks','sports goods','rare earth concept','renminbi appreciation concept','anti-epidemic concept','new stocks and sub-new stocks','Tencent concept', 'Cloud Office','SaaS Concept','Online Education','Auto Dealer','Norwegian Government Global Pension Fund Holding','Wuhan Local Concept Stock','Nuclear Power','Mainland Pharmaceutical Stock','Makeup and Beauty Stocks','Technology Internet Stocks','Utilities Stocks','Oil Stocks','Telecom Equipment','Power Stocks','Mobile Games Stocks','Baby and Children’s Products Stocks','Department Stocks', ' Rent collection stocks','port transportation stocks','telecommunications stocks','environmental protection','coal stocks','automotive stocks','battery stocks','logistics','mainland property management stocks','agricultural stocks', 'Golden stocks','luxury stocks','power equipment stocks','fast food chain stores','heavy machinery stocks','food stocks','insurance stocks','paper stocks','water affairs stocks' ,'Dairy products stocks','PV solar stocks','Chinese real estate stocks','Mainland education stocks','Home appliances stocks','Wind power stocks','Blue chip real estate stocks','Chinese banking stocks','Aviation stocks' ,'Petrochemical stocks','Building materials and cement stocks','Chinese brokerage stocks','High-speed rail infrastructure stocks','Gas stocks','Highway and railway stocks','Steel and metal stocks','Huawei concept','OLED Concept','Industrial hemp','Hong Kong local stocks','Hong Kong retail stocks','blockchain','pork concept','holiday concept','Funeral Concept']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Get Stock Basic Information

`get_stock_basicinfo(market, stock_type=SecurityType.STOCK, code_list=None)`

* **Description**

    Get Stock Basic Information

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type.
    stock_type|[SecurityType](./quote.md#9767)|Stock type. It does not support SecurityType.DRVT.
    code_list|list|Stock list.  (- The default is None, which means to get the static information of the stocks in the whole market.
  -  If the stock list is passed in, only the information of the specified stocks will be returned.
  - Support options.
  - Data type of elements in the list is str.)
    Note: when both *market* and *code_list* exist, *market* is ignored and only *code_list* is effective.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, stock static data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Stock static data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        lot_size|int|Number of shares per lot, number of shares per contract for options  (Index options do not have this field.), contract multipliers for futures.
        stock_type|[SecurityType](./quote.md#9767)|Stock type.
        stock_child_type|[WrtType](./quote.md#2421)|Warrant type.
        stock_owner|str|The code of the underlying stock to which the warrant belongs, or the code of the underlying stock of the option.
        option_type|[OptionType](./quote.md#9598)|Option type.
        strike_time|str|The option exercise date.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        strike_price|float|Option strike price.
        suspension|bool|Whether the option is suspended.  (True: suspension.False: not suspended.)
        listing_date|str|Listing time.  (This field is deprecated. Format: yyyy-MM-dd)
        stock_id|int|Stock ID.
        delisting|bool|Whether is delisted or not.
        index_option_type|str|Index option type.
        main_contract|bool|Whether is future main contract.
        last_trade_time|str|Last trading time.  (Main, current month and next month futures etc. do not have this field.)
        exchange_type|[ExchType](./quote.html#7268)|Exchange Type.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_stock_basicinfo(Market.HK, SecurityType.STOCK)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
print('******************************************')
ret, data = quote_ctx.get_stock_basicinfo(Market.HK, SecurityType.STOCK, ['HK.06998', 'HK.00700'])
if ret == RET_OK:
    print(data)
    print(data['name'][0]) # Take the first stock name
    print(data['name'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
        code             name  lot_size stock_type stock_child_type stock_owner option_type strike_time strike_price suspension listing_date        stock_id  delisting index_option_type  main_contract last_trade_time exchange_type
0      HK.00001     CK Hutchison       500      STOCK              N/A                                              N/A        N/A   2015-03-18   4440996184065      False               N/A          False                  HK_MAINBOARD 
...         ...              ...       ...        ...              ...         ...         ...         ...          ...        ...          ...             ...        ...               ...            ...             ...
2592   HK.09979     GREENTOWN MANAGEMENT HOLDINGS COMPANY LIMITED      1000      STOCK              N/A                                              N/A        N/A   2020-07-10  79203491915515      False               N/A          False                  HK_MAINBOARD               

[2593 rows x 16 columns]
******************************************
        code            name  lot_size stock_type stock_child_type stock_owner option_type strike_time strike_price suspension listing_date        stock_id  delisting index_option_type  main_contract last_trade_time exchange_type
0  HK.06998     JHBP       500      STOCK              N/A                                              N/A        N/A   2020-10-07  79572859099990      False               N/A          False                  HK_MAINBOARD               
1  HK.00700     Tencent       100      STOCK              N/A                                              N/A        N/A   2004-06-16  54047868453564      False               N/A          False                  HK_MAINBOARD               
JHBP
['JHBP', 'Tencent']
```

:::tip Tips
* When input stocks are not recognized by the program (including stocks that have been delisted a long time ago and non-existent stocks), this interface still returns stock information. The "delisted" field is used to indicate that the stock does exist or not. The unified processing is: the code is displayed normally, the stock name is displayed as "unknown stock", and the other fields are default values (The integer type defaults to 0, and the string defaults to an empty string.).
* This interface is different from other market information interfaces. When other interfaces get input stocks that the program cannot recognize, they will reject the request and return the error description "unknown stock".
* To obtain option data (e.g., Greeks,expiry,OI), please use [Get Market Snapshot](./get-market-snapshot.md).
:::

---

# Get IPO Information

`get_ipo_list(market)`

* **Description**

    Get IPO information of a specific market

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market identification.  (Note: Shanghai and Shenzhen are not distinguished here. Entering Shanghai or Shenzhen will return the stocks in the Shanghai and Shenzhen markets.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, IPO data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * IPO data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        list_time|str|Listing date, expected listing date for US stocks.  (Format：yyyy-MM-dd)
        list_timestamp|float|Listing date timestamp, expected listing date timestamp for US stocks.
        apply_code|str|Subscription code (applicable to A-shares).
        issue_size|int|Total number of issuance (applicable to A-shares); Total quantity of issuance (applicable to US stocks, SG, MY, JP).
        online_issue_size|int|Online issuance (applicable to A-shares).
        apply_upper_limit|int|Subscription limit (applicable for A-shares).
        apply_limit_market_value|int|The market value required for maximium subscription (applicable to A-shares).
        is_estimate_ipo_price|bool|Weather to estimate the issuance price (applicable to A-shares).
        ipo_price|float|Issuance price.  (Estimated value, for reference only, will change due to changes in data such as raised funds, issuance quantity, issuance costs, etc. The actual data will be updated as soon as it is released.) (applicable to A-shares).
        industry_pe_rate|float|Industry P/E ratio (applicable to A-shares).
        is_estimate_winning_ratio|bool|Whether to estimate the winning rate (applicable to A-shares).
        winning_ratio|float|Winning rate.  (- This field is in percentage form, so 20 is equivalent to 20%.
  - The estimated value, for reference only, will change due to changes in data such as funds raised, issuance quantity, issuance costs, etc. The actual data will be updated as soon as it is released.) (applicable to A-shares).
        issue_pe_rate|float|Issue P/E ratio (applicable to A-shares).
        apply_time|str|Subscription date string  (Format：yyyy-MM-dd) (applicable to A-shares).
        apply_timestamp|float|Subscription date timestamp (applicable to A-shares).
        winning_time|str|Time string of announcement date  (Format：yyyy-MM-dd) (applicable to A-shares, SG, MY).
        winning_timestamp|float|Timestamp of announcement date (applicable to A-shares, SG, MY).
        is_has_won|bool|Whether the winning number has been announced (applicable to A-shares).
        winning_num_data|str|The winning number (applicable to A-shares).  (The format is similar: The last "five" digits: 12345, 12346. The last "six" digits: 123456.) 
        ipo_price_min|float|Lowest offer price (applicable to HK stocks); lowest issue price (applicable to US stocks, SG, JP).
        ipo_price_max|float|Highest offer price (applicable to HK stocks); highest issue price (applicable to US stocks, SG, JP).
        list_price|float|List price (applicable to HK stocks).
        lot_size|int|Number of shares per lot.
        entrance_price|float|Entrance fee (applicable to HK stocks).
        is_subscribe_status|bool|Is it a subscription status.  (True: is subscribing, False: pending listing.) 
        apply_end_time|str|Subscription deadline string  (Format：yyyy-MM-dd) (applicable to HK stocks, SG, MY).
        apply_end_timestamp|float|Subscription deadline timestamp (applicable to HK stocks, SG, MY).
        apply_start_time|str|Subscription start date string (Format: yyyy-MM-dd) (applicable to SG, MY)
        apply_start_timestamp|float|Subscription start date timestamp (applicable to SG, MY)
        offer_price|float|Offer price (applicable to MY)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_ipo_list(Market.HK)
if ret == RET_OK:
    print(data)
    print(data['code'][0]) # Take the first stock code
    print(data['code'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code      name   list_time  list_timestamp apply_code issue_size online_issue_size apply_upper_limit apply_limit_market_value is_estimate_ipo_price ipo_price industry_pe_rate is_estimate_winning_ratio winning_ratio issue_pe_rate apply_time apply_timestamp winning_time winning_timestamp is_has_won winning_num_data  ipo_price_min  ipo_price_max  list_price  lot_size  entrance_price  is_subscribe_status apply_end_time  apply_end_timestamp  apply_start_time  apply_start_timestamp  offer_price
0  HK.06666  Evergrande Property Services Group Limited  2020-12-02    1.606838e+09        N/A        N/A               N/A               N/A                      N/A                   N/A       N/A              N/A                       N/A           N/A           N/A        N/A             N/A          N/A               N/A        N/A              N/A          8.500           9.75         0.0       500         4924.12                 True     2020-11-26         1.606352e+09               N/A                    N/A          N/A
1  HK.02110                    Yue Kan Holdings Limited  2020-12-07    1.607270e+09        N/A        N/A               N/A               N/A                      N/A                   N/A       N/A              N/A                       N/A           N/A           N/A        N/A             N/A          N/A               N/A        N/A              N/A          0.225           0.27         0.0     10000         2727.21                 True     2020-11-27         1.606439e+09               N/A                    N/A          N/A
HK.06666
['HK.06666', 'HK.02110']
```

::: tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Get global market status

`get_global_state()`  

* **Description**

    Get global status


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, global status is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Global status format as follows: 
        Field|Type|Description
        :-|:-|:-
        market_sz|[MarketState](./quote.md#8663)|Shenzhen market state.
        market_sh|[MarketState](./quote.md#8663)|Shanghai market state.
        market_hk|[MarketState](./quote.md#8663)|Hong Kong market status.
        market_hkfuture|[MarketState](./quote.md#8663)|Hong Kong futures market status.   (Due to there are differences in the trading time of different varieties in the US futures market, it is recommended to use [get_market_state](../quote/get-market-state.md) interface to get the market state of the specified variety.)
        market_usfuture|[MarketState](./quote.md#8663)|US futures market status.  (Due to there are differences in the trading time of different varieties in the US futures market, it is recommended to use [get_market_state](../quote/get-market-state.md) interface to get the market state of the specified variety.)
        market_us|[MarketState](./quote.md#8663)|United States market state.  (Due to there are differences in the trading time of different varieties in the US market, it is recommended to use [get_market_state](../quote/get-market-state.md) interface to get the market state of the specified variety.)
        market_sgfuture|[MarketState](./quote.md#8663)|Singapore futures market status.  (Due to there are differences in the trading time of different varieties in the Singapore futures market, it is recommended to use [get_market_state](../quote/get-market-state.md) interface to get the market state of the specified variety.)
        market_jpfuture|[MarketState](./quote.md#8663)|Japanese futures market status.
        market_sg|[MarketState](./quote.md#8663)|Singapore market state.
        market_my|[MarketState](./quote.md#8663)|Malaysia market state.
        market_jp|[MarketState](./quote.md#8663)|Japan market state.
        server_ver|str|OpenD version number.
        trd_logined|bool|True: Logged into the trading server, False: Not logged into the trading server.
        qot_logined|bool|True: logged into the market server, False: Not logged into the market server.
        timestamp|str|Current Greenwich timestamp.  (unit: second)
        local_timestamp|float|Local timestamp for OpenD.  (unit: second)
        program_status_type|[ProgramStatusType](../ftapi/common.md#9803)|Current status.
        program_status_desc|str|Additional description.
    

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
print(quote_ctx.get_global_state())
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
(0, {'market_sz': 'REST', 'market_us': 'AFTER_HOURS_END', 'market_sh': 'REST', 'market_hk': 'MORNING', 'market_hkfuture': 'FUTURE_DAY_OPEN', 'market_usfuture': 'FUTURE_OPEN', 'market_sgfuture': 'FUTURE_DAY_OPEN', 'market_jpfuture': 'FUTURE_DAY_OPEN', 'server_ver': '504', 'trd_logined': True, 'timestamp': '1620963064', 'qot_logined': True, 'local_timestamp': 1620963064.124152, 'program_status_type': 'READY', 'program_status_desc': ''})
```

---

# Get Trading Calendar

`request_trading_days(market=None, start=None, end=None, code=None)`

* **Description**

    Request trading calendar via market or code.  
    Note that the trading day is obtained by excluding weekends and holidays from natural days, and the temporary market closed data is not excluded.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    market|[TradeDateMarket](./quote.md#6587)|Market type.
    start|str|Start date.  (Format: yyyy-MM-dd
For example: "2018-01-01".)
    end|str|End date.  (Format: yyyy-MM-dd
For example: "2018-01-01".)
    code| str | Security code.
    Note: when both *market* and *code* exist, *market* is ignored and only *code* is effective.

    * The combination of ***start*** and ***end*** is as follows
        Start type|End type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 365 days before ***end***.
        str|None|***end*** is 365 days after ***start***.
        None|None|***start*** is 365 days before, ***end*** is the current date.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>list</td>
            <td>If ret == RET_OK, data of the trading day is returned. Data type of elements in the list is dict.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Data of the trading day's format as follows: 
        Field|Type|Description
        :-|:-|:-
        time|str|Time.  (Format: yyyy-MM-dd)
        trade_date_type|[TradeDateType](./quote.md#8930)|Trading day type.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.request_trading_days(TradeDateMarket.HK, start='2020-04-01', end='2020-04-10')
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
[{'time': '2020-04-01', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-02', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-03', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-06', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-07', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-08', 'trade_date_type': 'WHOLE'}, {'time': '2020-04-09', 'trade_date_type': 'WHOLE'}]
```

:::tip Interface Limitations
* A maximum of 30 requests per 30 seconds
* The historical trading calendar provides data for the past 10 years, and the future trading calendar is available until December 31 this year. (For example: today's date is July 6, 2021, and the period only from 2011-07-06 to 2021-12-31 is provided.)。
:::

---

﻿# Search Quotes

`get_search_quote(keyword, max_count=10)`

* **Description**

    Search quotes by keyword and return a list of matched securities.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    keyword|str|Search keyword
    max_count|int|Maximum number of items returned in this request  (Default 10, maximum 100)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns search quote list</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        market|[Market](./quote.md#456)|Market type
        code|str|Stock code
        name|str|Stock name
        sec_type|[SecurityType](./quote.md#9767)|Stock type
        is_watched|bool|In watchlist

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_search_quote('aapl',10)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
  market         code                        name sec_type  is_watched
0     US      US.AAPL                          苹果    STOCK        True
1     US      US.AAPB  2倍做多AAPL ETF-GraniteShares      ETF       False
2     US  US.LIST2139                        虚拟现实    PLATE       False
3     US  US.LIST2432                       流媒体概念    PLATE       False
4     US  US.LIST2437                        苹果概念    PLATE       False
5     JP      JP.2788         Apple International    STOCK       False
6     US      US.AAPI     APPLE ISPORTS GROUP INC    STOCK       False
7     SH    SH.603020                        爱普股份    STOCK       False
8     US      US.APLY      AAPL期权收益策略ETF-YieldMax      ETF       False
9     US      US.APRU      APPLE RUSH COMPANY INC    STOCK       False
```

:::tip API Restrictions
* Maximum 10 search quote requests per 30 seconds.
:::

---

﻿# Search News

`get_search_news(keyword, max_count=10, news_sub_type=NewsSubType.ALL)`

* **Description**

    Search news by keyword and return a list of matched news, notices, ratings, and other items.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    keyword|str|Search keyword
    max_count|int|Maximum number of items returned in this request  (Default 10, maximum 100)
    news_sub_type|[NewsSubType](./quote.md#1175)|News sub type  (Default NewsSubType.ALL)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns search news list</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        title|str|Title
        news_sub_type|[NewsSubType](./quote.md#1175)|News sub type
        source|str|Source
        publish_time|str|Publish time
        view_count|int|View count
        related_securities|list|Related securities
        url|str|Detail page URL

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_search_news('space', 10, news_sub_type=NewsSubType.ALL)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```

* **Output**

```python
                                               title news_sub_type       source publish_time  view_count related_securities                                                url
0                         Space：2026年12月期 第一财季业绩说明材料          NEWS        日本交易所         5/13         329                 []           https://news.futunn.com/notice/307288728
1               Space：2026年12月期 第一财季业绩简报[日本会计准则]（合并）          NEWS        日本交易所         5/13         277                 []           https://news.futunn.com/notice/307288725
2           SPACE CO., LTD. 第一季度盈利表现强劲，但全年利润和股息预期下调。          NEWS     TipRanks         5/13         201                 []  https://news.futunn.com/post/73007255?futusour...
3               New Street Research 开始覆盖太空经济和基础设施领域。          NEWS  PR Newswire         5/14        6035                 []  https://news.futunn.com/post/73047684?futusour...
4                                        Space：临时报告书          NEWS        日本金融厅         3/27         257                 []           https://news.futunn.com/notice/306761904
5                    Gemini Space Station | 8-K：重大事件        NOTICE      美股SEC公告         6/16         278          [US.GEMI]  https://news.futunn.com/notice/307532371?futus...
6  Extra Space Storage | 4：持股变动声明-高管 McNeal Gwyn ...        NOTICE      美股SEC公告         6/13         348           [US.EXR]  https://news.futunn.com/notice/307521769?futus...
7        Space Exploration Technologies Corp：承保或代理协议        NOTICE        SEDAR         6/12         400                 []  https://news.futunn.com/notice/307519369?futus...
8  Space Exploration Technologies Corp：补充长期形式的预备招...        NOTICE        SEDAR         6/12         231                 []  https://news.futunn.com/notice/307519371?futus...
9  Space Exploration Technologies Corp：补充长期形式的预备招...        NOTICE        SEDAR         6/12         210                 []  https://news.futunn.com/notice/307519370?futus...
```

:::tip API Restrictions
* Maximum 10 search news requests per 30 seconds.
:::

---

# Get Earnings Calendar

`get_earnings_calendar(market, sort_type=None, begin_date=None, end_date=None, filter_list=None)`

* **Description**

    Get earnings calendar, returning a list of stocks in a specified market that are about to or have already released earnings reports within a given date range, including earnings date, actual and estimated values for EPS/revenue/EBIT, option implied volatility, and other information.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (required)
    sort_type|[EarningsCalendarSortType](./quote-market.md#5545)|Sort type (default Hot)
    begin_date|str|Start date, format "yyyy-MM-dd", defaults to today if not provided (fetches only that day)
    end_date|str|End date, format "yyyy-MM-dd", if not provided only fetches beginDate; interval with beginDate must not exceed 7 days
    filter_list|list[`EarningsCalendarFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`EarningsCalendarFilter`）：**

      Construct filter conditions via `EarningsCalendarFilter`, supporting two filter modes:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`EarningsCalendarIndicatorType`, required) |
      | `value_list` | Exact value list (for enum-type filters such as release type, indicator type, stock list type) |
      | `interval_min` / `interval_max` | Min/max value for range filter |
      | `min_inclusive` / `max_inclusive` | Whether range boundaries are inclusive (default True) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        earnings_date|str|Earnings date ("yyyy-MM-dd")
        earnings_timestamp|float|Earnings release timestamp (Unix seconds)
        pub_type|str|Publish type (BEFORE=pre-market / AFTER=after-hours / REGULAR=intraday)
        period_text|str|Fiscal period (e.g. `'2025Q1'`)
        eps_actual|float|EPS actual value (available when published)
        eps_predict|float|EPS estimated value
        revenue_actual|float|Total revenue actual value (available when published)
        revenue_predict|float|Total revenue estimated value
        ebit_actual|float|EBIT actual value (available when published)
        ebit_predict|float|EBIT estimated value
        option_volume|int|Option volume (HK/US stocks only)
        iv|float|Implied volatility (%) (HK/US stocks only)
        iv_rank|float|IV rank (%) (HK/US stocks only)
        iv_percentile|float|IV percentile (%) (HK/US stocks only)
        market_cap|float|Real-time market cap
        price|float|Latest price

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_earnings_calendar(market=Market.US)
if ret == RET_OK:
    print(data.head(2))
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
security  name earnings_date  earnings_timestamp pub_type period_text eps_actual eps_predict revenue_actual revenue_predict ebit_actual   ebit_predict  option_volume       iv  iv_rank  iv_percentile    market_cap    price
0    US.MU  美光科技    2026-06-24        1.782331e+09    AFTER      2026Q3        N/A     20.8654            N/A   35251836320.0         N/A  26879423830.0         633420  113.795   97.754         98.015  1.186117e+12  1051.77
1  US.PAYX    沛齐    2026-06-24        1.782308e+09   BEFORE      2026Q4        N/A      1.2167            N/A    1606293190.0         N/A    661853410.0           6603   42.209   85.862         93.650  3.510892e+10    97.99
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Macro Indicator List

`get_macro_indicator_list(region)`

* **Description**

    Get macro indicator list. Returns the macro economic indicator categories and indicator information for the specified country/region, including indicator ID and name, for subsequent historical data queries.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    region|[MacroRegion](./quote-market.md#5420)|Country/region (required)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        category_name|str|Category name (e.g. "All"/"Employment"/"Inflation"/"Interest Rate")
        indicator_id|int|Macro indicator ID (for querying historical data)
        name|str|Indicator name

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_macro_indicator_list(region=MacroRegion.US)
if ret == RET_OK:
    print(data.head(2))
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
category_name  indicator_id              name
0            物价    1003000003  美国生产者物价指数(PPI)同比
1            物价    1003000001         美国核心CPI同比
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Macro Indicator History

`get_macro_indicator_history(indicator_id, time=None, max_count=None)`

* **Description**

    Get macro indicator history. Returns the historical data point list of the specified macro indicator, including data date, release date, actual value, forecast value, previous value, etc., sorted by time in descending order.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    indicator_id|int|Macro indicator ID (from `get_macro_indicator_list` return) (required)
    time|str|Time point, format "yyyy-MM-dd", pulls data before this time; defaults to current time if not provided
    max_count|int|Number of records to pull, default 100, maximum 1000

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        data_time|str|Data date ("yyyy-MM-dd")
        release_time|str|Release date ("yyyy-MM-dd HH:mm:ss")
        value|float|Actual value (restored to original value)
        predict_value|float|Forecast value (restored)
        previous_value|float|Previous value (restored)
        unit_type|str|Unit type (PERCENT=percentage / VALUE=value / INDEX=index)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# First get indicator ID
ret, indicators = quote_ctx.get_macro_indicator_list(region=MacroRegion.US)
if ret == RET_OK:
    indicator_id = indicators.iloc[0]['indicator_id']

    # Query historical data
    ret, data = quote_ctx.get_macro_indicator_history(indicator_id=indicator_id, max_count=2)
    if ret == RET_OK:
        print(data)
    else:
        print('error:', data)

quote_ctx.close()
```

* **Output**

```
data_time         release_time   value predict_value  previous_value unit_type
0  2026-05-01  2026-06-11 20:34:01  0.0642           N/A          0.0566   PERCENT
1  2026-04-01  2026-05-13 20:31:01  0.0566           N/A          0.0427   PERCENT
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get FedWatch Target Rate

`get_fed_watch_target_rate()`

* **Description**

    Get CME FedWatch federal funds target rate probability forecast data. Returns the target rate range and market-implied probability distribution for each FOMC meeting, sourced from CME federal funds futures pricing.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        meeting_date|str|FOMC meeting date ("yyyy-MM-dd")
        target_range|str|Target rate range, e.g. "4.25% ~ 4.50%"
        probability|float|Market expected probability (%), e.g. 92.13 means 92.13%

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_fed_watch_target_rate()
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
meeting_date target_range  probability
0   2026-07-29   3.50-3.75%         62.6
1   2026-07-29   3.75-4.00%         37.4
2   2026-09-16   3.50-3.75%         29.8
3   2026-09-16   3.75-4.00%         50.6
4   2026-09-16   4.00-4.25%         19.6
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get FedWatch Dot Plot

`get_fed_watch_dot_plot()`

* **Description**

    Get CME interest rate dot plot data. Returns the voting distribution of FOMC members' expected federal funds rate for future years, including the number of votes at each rate level, median rate, and current federal funds rate.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        year|int|Forecast year, e.g. 2025, 2026, 2027
        rate|float|Expected rate (%), e.g. 4.125 means 4.125%
        vote_count|int|Number of members voting at this rate level
        is_median|bool|Whether this is the median rate for the year
        median_rate|float|Median rate for the year (%)
        current_rate|float|Current federal funds rate (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_fed_watch_dot_plot()
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
year   rate  vote_count  is_median  median_rate  current_rate
0  2026  3.375           1      False        3.875          3.63
1  2026  3.625           8      False        3.875          3.63
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Earnings Beat Rank

`get_earnings_beat_rank(market, beat_type, count=None, term=None, filter_list=None, sort_field=None)`

* **Description**

    Get earnings beat rank, returning a list of stocks in a specified market where actual earnings exceeded estimates, including beat ratio, first-day price change after earnings, year-over-year growth rate, and other dimensional data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (supports HK/US/SG/JP) (required)
    beat_type|[BeatType](./quote-market.md#2212)|Beat type (required)
    count|int|Return count [1, 300], default 30
    term|[BeatTerm](./quote-market.md#6568)|Earnings report period, default ALL
    filter_list|list[`EarningsBeatRankFilter`]|Filter condition list (multiple conditions are AND-combined)
    sort_field|[EarningsBeatSortField](./quote-market.md#3630)|Sort field (fixed descending), default by market cap

* **Input Limits**

    - **`filter_list` Filter Conditions（`EarningsBeatRankFilter`）：**

      Construct filter conditions via `EarningsBeatRankFilter`, supporting range filter only:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`EarningsBeatIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval) |
      | `interval_max` | Range maximum (closed interval) |

      When `filter_list` is not provided, default filter is applied: beat ratio > 0, release time within the last 30 days.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        industry|str|Industry
        cur_price|float|Latest price
        last_close_price|float|Previous close price
        change_rate|float|Today's change rate (%)
        market_cap|float|Market cap
        pe_ttm|float|P/E ratio TTM
        dividends_ttm|float|Dividend yield TTM (%)
        released_date|str|Earnings release date (e.g. `'2024-01-15'`)
        beat_ratio|float|Beat ratio (%)
        actual|float|Actual value
        estimate|float|Estimate value
        yoy|float|Year-over-year
        yoy_growth|float|YoY growth rate (%)
        earning_day_chg|float|First-day change after earnings (%)
        term|str|Earnings period (e.g. `'2024/Q1'`)
        detail_post_period|str|Publish period (BEFORE=pre-market / AFTER=after-hours / REGULAR=intraday / INTRADAY_TRADING=intraday trading)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_earnings_beat_rank(market=Market.US, beat_type=BeatType.EPS, count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 1276
  security name industry  cur_price  last_close_price  change_rate    market_cap    pe_ttm  dividends_ttm released_date  beat_ratio  actual  estimate   yoy  yoy_growth  earning_day_chg     term detail_post_period
0  US.NVDA  英伟达      半导体     200.04            208.65       -4.126  4.840968e+12  30.63399          0.019    2026-05-20      37.253  2.3900    1.7413  0.76     214.473           -1.772  2027/Q1              AFTER
1  US.AAPL   苹果   消费电子产品     294.30            297.01       -0.912  4.322489e+12  35.62953          0.353    2026-04-30       3.373  2.0099    1.9444  1.65      21.818            3.239  2026/Q2              AFTER
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Dividend Rank

`get_dividend_rank(market, rank_type, count=None, filter_list=None, sort_field=None)`

* **Description**

    Get dividend rank, returning a list of stocks in a specified market ranked by high dividend yield or consecutive dividend growth, including dividend yield, distribution frequency, consecutive growth years, and other dimensional data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (supports HK/US/MY/SG/JP) (required)
    rank_type|[DividendRankType](./quote-market.md#3863)|Rank type (required)
    count|int|Return count [1, 300], default 10
    filter_list|list[`DividendRankFilter`]|Filter condition list (multiple conditions are AND-combined, supports range and enum types)
    sort_field|[DividendRankSortField](./quote-market.md#5656)|Sort field (fixed descending), default determined by rankType

* **Input Limits**

    - **`filter_list` Filter Conditions（`DividendRankFilter`）：**

      Construct filter conditions via `DividendRankFilter`, supporting both **range** and **enum** filters:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`DividendRankIndicatorType`, required) |
      | `value_list` | Enum value list (for enum-type filters, such as dividend frequency) |
      | `interval_min` | Range minimum (closed interval, for range filter) |
      | `interval_max` | Range maximum (closed interval, for range filter) |

      > Note: At least one of `value_list` or `interval_min/interval_max` must be provided.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'HK.00005'`)
        name|str|Stock name
        industry|str|Industry
        cur_price|float|Latest price
        change_rate|float|Today's change rate (%)
        change_amount|float|Today's change amount
        market_cap|float|Market cap
        dividend_yield_ttm|float|Dividend yield TTM (%)
        avg_dividend_yield_5y|float|5-year average dividend yield (%)
        distribution_frequency|str|Distribution frequency (ANNUAL/SEMI_ANNUAL/QUARTERLY/MONTHLY), not supported for HK market
        dividend_grow_year|int|Consecutive dividend growth years
        dividends_ttm|float|Dividends TTM (amount)
        payout_ratio_lfy|float|Dividend payout ratio LFY (%)
        next_payable_date|str|Next dividend date (e.g. `'2025-09-15'`)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_dividend_rank(market=Market.HK, rank_type=DividendRankType.HIGH_YIELD, count=2)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
security  name industry  cur_price  change_rate  change_amount    market_cap  dividend_yield_ttm  avg_dividend_yield_5y distribution_frequency  dividend_grow_year  dividends_ttm  payout_ratio_lfy next_payable_date
0  HK.00288  万洲国际     包装食品       8.54       -0.582          -0.05  1.095701e+11              10.655                 10.855            SEMI_ANNUAL                   2          0.910            116.44               N/A
1  HK.01919  中远海控    航运及港口      13.20       -1.123          -0.15  2.021314e+11               8.522                 38.168            SEMI_ANNUAL                   0          1.125             49.67               N/A
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Dividend Calendar

`get_dividend_calendar(market, date, data_from=None, count=None)`

* **Description**

    Get dividend calendar, returning a list of dividend data for a specific day in a given market, including ex-dividend date, record date, dividend payable date, and other information.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (supports HK/US/MY/SG/JP) (required)
    date|str|Query date, format `"YYYY-MM-DD"` (required)
    data_from|int|Page offset, default 0
    count|int|Return count, default unlimited

* **Input Limits**

    - **`date`**：Only supports querying single-day data, format `"YYYY-MM-DD"`.

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'HK.00005'`)
        name|str|Stock name
        statement|str|Dividend plan description
        record_date|str|Record date (`"YYYY-MM-DD"`)
        ex_date|str|Ex-dividend date (`"YYYY-MM-DD"`)
        dividend_payable_date|str|Dividend payable date (`"YYYY-MM-DD"`)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_dividend_calendar(market=Market.US, date='2026-06-24', count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 225
  security              name      statement record_date     ex_date dividend_payable_date
0   US.STX              希捷科技    1股派息0.74USD  2026-06-24  2026-06-24            2026-07-07
1   US.VGT  资讯科技ETF-Vanguard  1股派息0.1384USD  2026-06-24  2026-06-24            2026-06-26
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Economic Calendar

`get_economic_calendar(begin_date, end_date=None, market_list=None,
                                       importance=None, count=None, next_page=None)`

* **Description**

    Get economic event calendar, returning economic data release events within a specified date range, including event title, release time, country, importance star rating, previous value, forecast value, and actual published value. Supports filtering by market and importance, and supports pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    begin_date|str|Start date, format "yyyy-MM-dd" (required)
    end_date|str|End date, format "yyyy-MM-dd"; if not provided, only queries begin_date
    market_list|list[Market]|Market filter (multi-select, supports HK/US/SH/SG/JP/AU/MY/CA), if not provided returns all markets
    importance|[EconomicImportance](./quote-market.md#3053)|Event importance filter, default ALL
    count|int|Per page count, default 50, max 100
    next_page|str|Page marker, do not provide for first request, pass the next_page from previous response afterwards

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        title|str|Event title (e.g. "Non-Farm Payrolls")
        timestamp|float|Release timestamp (seconds)
        country|str|Country name
        star|str|Importance star rating ("LOW"/"MEDIUM"/"HIGH")
        previous|str|Previous value ("--" if not available)
        consensus|str|Forecast value ("--" if not available)
        actual|str|Actual published value ("--" if not available)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, has_more = quote_ctx.get_economic_calendar(begin_date='2026-06-23', end_date='2026-06-24', count=2)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
title     timestamp country    star previous consensus actual
0   日本6月综合PMI初值  1.782175e+09      日本  MEDIUM                          
1  日本6月制造业PMI初值  1.782175e+09      日本  MEDIUM
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get US Pre-Market Rank

`get_us_pre_market_rank(sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get US pre-market rank, returning pre-market trading session change rate rankings, including pre-market price, change rate, turnover, volume, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending (top gainers)
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`SimpleRankFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`SimpleRankFilter`）：**

      Construct filter conditions via `SimpleRankFilter`:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`SimpleRankIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval, for MARKET_CAP/PE) |
      | `interval_max` | Range maximum (closed interval, for MARKET_CAP/PE) |
      | `price_filter` | Price filter enum (`PriceFilter`, required for PRICE type) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        pre_market_price|float|Pre-market price
        pre_market_change_ratio|float|Pre-market change rate (%)
        pre_market_change_amount|float|Pre-market change amount
        pre_market_turnover|float|Pre-market turnover
        pre_market_volume|int|Pre-market volume
        close_price|float|Close price (previous trading day)
        change_ratio|float|Intraday change rate (%)
        change_amount|float|Intraday change amount

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_us_pre_market_rank(count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 17728
  security                    name  pre_market_price  pre_market_change_ratio  pre_market_change_amount  pre_market_turnover  pre_market_volume  close_price  change_ratio  change_amount
0  US.ATLN  Atlantic International              1.18                  168.303                      0.74         1.219515e+08          136776297         1.33    202.961276          0.891
1  US.BOLD           Boundless Bio              2.40                   71.428                      1.00         6.180064e+07           25082585         2.60     85.714286          1.200
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get US After-Hours Rank

`get_us_after_hours_rank(sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get US after-hours rank, returning after-hours trading session change rate rankings, including after-hours price, change rate, turnover, volume, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending (top gainers)
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`SimpleRankFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`SimpleRankFilter`）：**

      Construct filter conditions via `SimpleRankFilter`:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`SimpleRankIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval, for MARKET_CAP/PE) |
      | `interval_max` | Range maximum (closed interval, for MARKET_CAP/PE) |
      | `price_filter` | Price filter enum (`PriceFilter`, required for PRICE type) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.TSLA'`)
        name|str|Stock name
        after_hours_price|float|After-hours price
        after_hours_change_ratio|float|After-hours change rate (%)
        after_hours_change_amount|float|After-hours change amount
        after_hours_turnover|float|After-hours turnover
        after_hours_volume|int|After-hours volume
        close_price|float|Close price (previous trading day)
        change_ratio|float|Intraday change rate (%)
        change_amount|float|Intraday change amount

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_us_after_hours_rank(count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 17728
  security                   name  after_hours_price  after_hours_change_ratio  after_hours_change_amount  after_hours_turnover  after_hours_volume  close_price  change_ratio  change_amount
0   US.MGN                  Megan               0.33                    92.048                      0.158          2.811130e+07            90547558        0.172     30.303030           0.04
1  US.QNRX  Quoin Pharmaceuticals               4.85                    49.230                      1.600          1.498305e+07             3050404        3.250    -26.303855          -1.16
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get US Overnight Rank

`get_us_overnight_rank(sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get US overnight rank, returning overnight trading session change rate rankings, including overnight price, change rate, turnover, volume, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending (top gainers)
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`SimpleRankFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`SimpleRankFilter`）：**

      Construct filter conditions via `SimpleRankFilter`:

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`SimpleRankIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval, for MARKET_CAP/PE) |
      | `interval_max` | Range maximum (closed interval, for MARKET_CAP/PE) |
      | `price_filter` | Price filter enum (`PriceFilter`, required for PRICE type) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.NVDA'`)
        name|str|Stock name
        overnight_price|float|Overnight price
        overnight_change_ratio|float|Overnight change rate (%)
        overnight_change_amount|float|Overnight change amount
        overnight_turnover|float|Overnight turnover
        overnight_volume|int|Overnight volume
        close_price|float|Close price (previous trading day)
        change_ratio|float|Intraday change rate (%)
        change_amount|float|Intraday change amount

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_us_overnight_rank(count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 17728
  security                   name  overnight_price  overnight_change_ratio  overnight_change_amount  overnight_turnover  overnight_volume  close_price  change_ratio  change_amount
0   US.MGN                  Megan           0.3128                  81.543             1.405000e+08         1681274.123           5102016        0.172     30.303030           0.04
1  US.QNRX  Quoin Pharmaceuticals           5.2900                  62.769             2.040000e+09         1164463.400            223649        3.250    -26.303855          -1.16
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Top Movers Rank

`get_top_movers_rank(market, sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get top movers rank (intraday), returning intraday trading session change rate rankings, supporting HK and US stocks, including latest price, change rate, turnover, turnover rate, P/E ratio, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending (top gainers)
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`SimpleRankFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`SimpleRankFilter`）：**

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`SimpleRankIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval, for MARKET_CAP/PE) |
      | `interval_max` | Range maximum (closed interval, for MARKET_CAP/PE) |
      | `price_filter` | Price filter enum (`PriceFilter`, required for PRICE type) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'HK.00700'`)
        name|str|Stock name
        cur_price|float|Latest price
        change_ratio|float|Change rate (%)
        change_amount|float|Change amount
        turnover|float|Turnover
        volume|int|Volume
        turnover_ratio|float|Turnover rate (%)
        pe_ttm|float|P/E ratio TTM
        amplitude|float|Amplitude (%)
        market_cap|float|Market cap
        volume_ratio|float|Volume ratio

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_top_movers_rank(market=Market.US, count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 1794
   security        name  cur_price  change_ratio  change_amount      turnover   volume  turnover_ratio  pe_ttm  amplitude    market_cap  volume_ratio
0    US.QNT  Quantinuum      77.46     13.461257           9.19  4.257190e+08  5582936          175.45  -8.523     225.28  2.020045e+10         1.540
1  US.NJDCY   日本电产(ADR)       3.90      9.859155           0.35  4.051129e+04     9816            0.00  24.074     225.35  1.788243e+10         0.426
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Hot List

`get_hot_list(market, sort_field=None, sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get hot list, returning a list of stocks ranked by popularity in a specified market, supporting sorting by trade heat, search heat, news heat, and comprehensive heat, with market cap filtering.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    sort_field|[HotListSortField](./quote-market.md#5175)|Sort field, default comprehensive heat
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`HotListFilter`]|Filter condition list (market cap)

* **Input Limits**

    - **`filter_list` Filter Conditions（`HotListFilter`）：**

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`HotListIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval) |
      | `interval_max` | Range maximum (closed interval) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.TSLA'`)
        name|str|Stock name
        trade_heat|float|Trade heat
        trade_heat_change|float|Trade heat change
        search_heat|float|Search heat
        search_heat_change|float|Search heat change
        news_heat|float|News heat
        news_heat_change|float|News heat change
        average_heat|float|Comprehensive heat
        average_heat_change|float|Comprehensive heat change
        news_type|str|News type ("Community"=community discussion, "News"=news)
        news_title|str|News/discussion title
        news_url|str|News URL (valid when news_type="News")

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_hot_list(market=Market.US, count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 6342
  security    name  trade_heat  trade_heat_change  search_heat  search_heat_change  news_heat  news_heat_change  average_heat  average_heat_change news_type                                         news_title                                           news_url
0  US.SPCX  SpaceX   9999995.0                0.0    9999972.0                 0.0  9999998.0               0.0     9999988.0                  0.0      News  SpaceX收涨1%，终结三连跌！首发债券获约3.6...  https://news.futunn.com/post/55589925?lang=...
1    US.MU    美光科技   5578115.0                0.0    7923445.0                 0.0  1835896.0              -2.0     5112485.0                  0.0       N/A                                              N/A                                              N/A
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Short Selling Rank

`get_short_selling_rank(market=None, sort_field=None, sort_dir=None, count=10, offset=None, plate_list=None)`

* **Description**

    Get short selling rank, returning US/HK stock short selling data rankings, supporting 14 sorting dimensions and industry sector filtering, including short selling volume, ratio, short position, days to cover, and other data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US), default US
    sort_field|[ShortSellingSortField](./quote-market.md#793)|Sort field, default short selling change
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 35], default 10
    offset|int|Start position, default 0
    plate_list|list[str]|Industry sector code list (e.g. `['US.BK2024']`), empty=all

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.GME'`)
        name|str|Stock name
        close_price|float|Close price
        change_ratio|float|Change rate (%)
        change_ratio_5d|float|5-day change rate (%)
        change_ratio_10d|float|10-day change rate (%)
        volume|int|Volume
        short_number|int|Short selling volume
        short_number_change|int|Short selling change
        short_ratio|float|Short selling ratio (%)
        short_ratio_change|float|Short selling ratio change (%)
        short_position_volume|int|Short position volume
        short_position_ratio|float|Short position ratio (%)
        days_to_cover|float|Days to cover
        week_avg_short_number|int|Weekly average daily short volume
        week_avg_short_ratio|float|Weekly average daily short ratio (%)
        month_avg_short_number|int|Monthly average daily short volume
        month_avg_short_ratio|float|Monthly average daily short ratio (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_short_selling_rank(count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 0
  security           name  close_price  change_ratio  change_ratio_5d  change_ratio_10d     volume  short_number  short_number_change  short_ratio  short_ratio_change  short_position_volume  short_position_ratio  days_to_cover  week_avg_short_number  week_avg_short_ratio  month_avg_short_number  month_avg_short_ratio
0  US.SKYQ     Sky Quarry       1.9000         62.39            45.03              4.39  221413731      20302431             20226903         9.16            26780.66                 327119                  6.82            1.0                4111613                  9.19                 1136188                   8.26
1  US.TNON  Tenon Medical       0.6215         77.57             0.72              2.89  271138156      15289764             15273389         5.63            93272.60                 149174                  1.28            2.9                3063337                  5.01                  772705                   5.04
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Period Change Rank

`get_period_change_rank(market, period_type=None, sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get period change rank, returning change rate rankings in a specified market by different time periods (5 minutes to 250 days/year-to-date), supporting rich filter conditions (market cap, price, PE, PB, turnover rate, volume ratio, amplitude, etc.).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    period_type|[RankPeriodType](./quote-market.md#1138)|Rank period, default 5 minutes
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`PeriodChangeRankFilter`]|Filter condition list (multiple conditions are AND-combined)

* **Input Limits**

    - **`filter_list` Filter Conditions（`PeriodChangeRankFilter`）：**

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`PeriodChangeIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval) |
      | `interval_max` | Range maximum (closed interval) |

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        cur_price|float|Latest price
        change_ratio|float|Today's change rate (%)
        turnover|float|Turnover
        volume|int|Volume
        market_cap|float|Market cap
        change_rate_5min|float|5-minute change rate (%)
        change_rate_5d|float|5-day change rate (%)
        change_rate_10d|float|10-day change rate (%)
        change_rate_20d|float|20-day change rate (%)
        change_rate_60d|float|60-day change rate (%)
        change_rate_120d|float|120-day change rate (%)
        change_rate_250d|float|250-day change rate (%)
        change_rate_ytd|float|Year-to-date change rate (%)
        pe_ttm|float|P/E ratio TTM
        pb|float|P/B ratio
        turnover_ratio|float|Turnover rate (%)
        volume_ratio|float|Volume ratio
        amplitude|float|Amplitude (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_period_change_rank(market=Market.US, count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 6429
  security                           name  cur_price  change_ratio  turnover  volume   market_cap  change_rate_5min  change_rate_5d  change_rate_10d  change_rate_20d  change_rate_60d  change_rate_120d  change_rate_250d  change_rate_ytd   pe_ttm       pb  turnover_ratio  volume_ratio  amplitude
0   US.JYD                         佳裕达物流       0.93        11.537  271197.0  311313   7717977.00             9.540           32.80           30.875           20.779          -68.150           -80.128           -90.610          -81.374 -0.40558  0.49892           5.220         0.732      20.94
1  US.RAIN  Rain Enhancement Technologies       2.23        19.892  112286.0   56451  18261097.59             9.313           -2.62            1.826           -6.302          -21.754           -71.914           -22.299          -61.815 -1.79838 -1.27283           2.812         0.816      27.15
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limit
:::

---

# Get High Dividend SOE Rank

`get_high_dividend_soe_rank(sort_field=None, sort_dir=None, count=10, offset=None, filter_list=None)`

* **Description**

    Get high dividend SOE rank (HK stocks), returning HK stock ranking data meeting default conditions: SOE value concept sector, PB<=1, dividend yield TTM>=5%, PE>=0. Users can override default thresholds via filter conditions.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    sort_field|[HighDividendSOESortField](./quote-market.md#8598)|Sort field, default market cap
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 10
    offset|int|Start position, default 0
    filter_list|list[`HighDividendSOERankFilter`]|Filter condition list (can override default conditions)

* **Input Limits**

    - **`filter_list` Filter Conditions（`HighDividendSOERankFilter`）：**

      | Constructor Parameter | Description |
      |----------|------|
      | `indicator_type` | Filter indicator type (`HighDividendSOEIndicatorType`, required) |
      | `interval_min` | Range minimum (closed interval) |
      | `interval_max` | Range maximum (closed interval) |

    - **Server-side default fixed conditions:**
      - Concept sector = SOE (State-Owned Enterprise) value stocks
      - P/B ratio <= 1
      - Dividend yield TTM >= 5%
      - P/E ratio >= 0

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns (all_count, DataFrame) tuple</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'HK.00857'`)
        name|str|Stock name
        industry|str|Industry
        cur_price|float|Latest price
        change_ratio|float|Change rate (%)
        turnover|float|Turnover
        volume|int|Volume
        market_cap|float|Market cap
        pe_ttm|float|P/E ratio TTM
        pb|float|P/B ratio
        dividend_yield_ttm|float|Dividend yield TTM (%)
        turnover_ratio|float|Turnover rate (%)
        change_rate_5d|float|5-day change rate (%)
        change_rate_10d|float|10-day change rate (%)
        change_rate_20d|float|20-day change rate (%)
        change_rate_60d|float|60-day change rate (%)
        change_rate_120d|float|120-day change rate (%)
        change_rate_250d|float|250-day change rate (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_high_dividend_soe_rank(count=2)
if ret == RET_OK:
    all_count, df = data
    print(f'Total count: {all_count}')
    print(df)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
总数据量: 98
   security    name industry  cur_price  change_ratio     turnover    volume    market_cap   pe_ttm       pb  dividend_yield_ttm  turnover_ratio  change_rate_5d  change_rate_10d  change_rate_20d  change_rate_60d  change_rate_120d  change_rate_250d
0  HK.01398    工商银行       银行        6.9        -0.862  325569646.0  46871758  2.459203e+12  5.84745  0.55072               5.072           0.054          -3.894           -0.288            1.917            9.411            16.416            24.292
1  HK.00857  中国石油股份    油气生产商        8.9        -0.447  154397506.0  17228406  1.628887e+12  9.09090  0.88539               5.932           0.081          -6.342          -10.216          -16.217          -14.691            14.209            36.468
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Institution List

`get_institution_list(market, sort_field=None, sort_dir=None, count=None, page=None, name_part=None)`

* **Description**

    Get institution list, returning a list of institutions ranked by position value/position change/holding count in a specified market, supporting fuzzy search and cursor pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    sort_field|[InstitutionListSortField](./quote-market.md#3881)|Sort field, default position value
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 20
    page|str|Page cursor, do not provide for first request, pass next_page from previous response
    name_part|str|Institution name fuzzy search

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        institution_id|int|Institution ID
        institution_name|str|Institution name
        position_value|float|Position value
        position_value_change|float|Position value change
        position_count|int|Position stock count
        position_count_change|int|Position stock count change
        disclosure_date|str|Disclosure date (yyyy-MM-dd)
        currency|str|Currency

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_institution_list(market=Market.US, count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 17030
   institution_id                  institution_name  position_value  position_value_change  position_count  position_count_change disclosure_date currency
0          403413                               贝莱德    6.959193e+12           3.432083e+10            4443                     56      2026-06-19      USD
1      1951572549  Vanguard Capital Management, LLC    4.881261e+12           4.492246e+12            4289                   3859      2026-06-10      USD
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Institution Profile

`get_institution_profile(market, institution_id)`

* **Description**

    Get institution profile, returning the specified institution's position value, position change statistics, Top10 holding percentage, and other profile data.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    institution_id|int|Institution ID (from get_institution_list) (required)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dictionary data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        institution_name|str|Institution name
        description|str|Institution description
        position_value|float|Position value
        last_position_value|float|Previous period position value
        position_value_change_pct|float|Value change percentage (%)
        total_holding_count|int|Total holding count
        holding_change_count|int|Holding change count
        new_count|int|New position count
        sold_out_count|int|Sold out count
        increase_count|int|Increase count
        decrease_count|int|Decrease count
        top10_pct|float|Top10 holding percentage (%)
        top10_pct_change|float|Top10 percentage change (%)
        disclosure_date|str|Disclosure date (yyyy-MM-dd)
        currency|str|Currency

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# First get institution ID
ret, data, _, _ = quote_ctx.get_institution_list(market=Market.US, count=1)
if ret == RET_OK and len(data) > 0:
    inst_id = data.iloc[0]['institution_id']

    # Query institution profile
    ret, profile = quote_ctx.get_institution_profile(market=Market.US, institution_id=inst_id)
    if ret == RET_OK:
        for k, v in profile.items():
            print(f"{k}: {v}")
    else:
        print('error:', profile)

quote_ctx.close()
```

* **Output**

```
institution_name: 贝莱德
description: 贝莱德集团是美国规模最大的资产管理集团之一，提供种类繁多的证券、固定收益、现金管理等投资产品。
position_value: 6959192681765.731
last_position_value: 6093992885377.756
position_value_change_pct: 14.1975
total_holding_count: 4443
holding_change_count: 12
new_count: 87
sold_out_count: 31
increase_count: 2364
decrease_count: 1682
top10_pct: 24.3287
top10_pct_change: 0.4142
disclosure_date: 2026-06-19
currency: USD
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Institution Distribution

`get_institution_distribution(market, institution_id)`

* **Description**

    Get institution distribution, returning the specified institution's position value and percentage data by industry classification.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    institution_id|int|Institution ID (obtained from get_institution_list) (required)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        industry_id|int|Industry ID
        industry_name|str|Industry name
        position_value|float|Holding market value
        portfolio_pct|float|Industry proportion (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# First get institution ID
ret, data, _, _ = quote_ctx.get_institution_list(market=Market.US, count=1)
if ret == RET_OK and len(data) > 0:
    inst_id = data.iloc[0]['institution_id']

    # Query industry distribution
    ret, data = quote_ctx.get_institution_distribution(market=Market.US, institution_id=inst_id)
    if ret == RET_OK:
        print(data)
    else:
        print('error:', data)

quote_ctx.close()
```

* **Output**

```
industry_id industry_name        position_value  portfolio_pct
0           6            电子  1319006433351.533936        19.8494
1          26           计算机   992844462205.649048        14.9411
2          12          医药生物   633746255374.343994         9.5371
3          27        互联网与传媒   484195469416.382996         7.2865
4          19          非银金融   481223610387.026001         7.2418
5         N/A            其他                   N/A        41.1441
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Institution Holding Change

`get_institution_holding_change(market, institution_id, change_type=None, sort_field=None, sort_dir=None, count=None, page=None)`

* **Description**

    Get institution holding changes, returning holding change records of the specified institution filtered by change type (open position/close position/increase/decrease), with support for sorting and cursor-based pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    institution_id|int|Institution ID (required)
    change_type|[InstitutionHoldingChangeType](./quote-market.md#8493)|Change type, default open position
    sort_field|[InstitutionHoldingChangeSortField](./quote-market.md#3464)|Sort field, default change percentage
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Number of results [1, 200], default 20
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        portfolio_pct|float|Holding proportion (%)
        change_shares|int|Changed shares
        change_pct|float|Change percentage (%)
        holding_date|int|Holding date (timestamp)
        source|str|Disclosure source

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# First get institution ID
ret, data, _, _ = quote_ctx.get_institution_list(market=Market.US, count=1)
if ret == RET_OK and len(data) > 0:
    inst_id = data.iloc[0]['institution_id']

    # Query holding changes
    ret, data, next_page, all_count = quote_ctx.get_institution_holding_change(
        market=Market.US, institution_id=inst_id, count=2)
    if ret == RET_OK:
        print(f'Total count: {all_count}')
        print(data)
    else:
        print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 87
  security                name  portfolio_pct  change_shares  change_pct holding_date source
0   US.YSS  York Space Systems        14.6594       19012439     14.6594   2026-03-30    13F
1  US.VSNT       Versant Media        12.2661       17356403     12.2661   2026-03-30    13F
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Institution Holding List

`get_institution_holding_list(market, institution_id, change_type=None, sort_field=None, sort_dir=None, count=None, page=None, keyword=None)`

* **Description**

    Get institution holding list, returning the complete holding details of the specified institution (including market value, holding proportion, changes, etc.), with support for filtering by change type, multi-dimensional sorting, and keyword search.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (HK/US) (required)
    institution_id|int|Institution ID (required)
    change_type|[InstitutionHoldingChangeType](./quote-market.md#8493)|Filter by change type (all if not provided)
    sort_field|[InstitutionHoldingListSortField](./quote-market.md#1650)|Sort field, default holding market value
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Number of results [1, 200], default 20
    page|str|Page cursor
    keyword|str|Search keyword (stock name/code)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name
        industry_name|str|Industry
        holding_value|float|Holding market value
        holding_pct|float|Holding proportion - percentage of total stock market cap (%)
        last_holding_pct|float|Previous period holding proportion (%)
        change_shares|int|Changed shares
        portfolio_pct|float|Proportion of institution total position (%)
        change_pct|float|Change percentage (%)
        holding_date|int|Holding date (timestamp)
        source|str|Disclosure source
        currency|str|Currency

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# First get institution ID
ret, data, _, _ = quote_ctx.get_institution_list(market=Market.US, count=1)
if ret == RET_OK and len(data) > 0:
    inst_id = data.iloc[0]['institution_id']

    # Query holding list
    ret, data, next_page, all_count = quote_ctx.get_institution_holding_list(
        market=Market.US, institution_id=inst_id, count=2)
    if ret == RET_OK:
        print(f'Total count: {all_count}')
        print(data)
    else:
        print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 4430
  security name industry_name  holding_value  holding_pct  last_holding_pct  change_shares  portfolio_pct  change_pct holding_date source currency
0  US.NVDA  英伟达            电子   3.887350e+11       7.9295            7.8996      -19284971         4.9289     -0.0796   2026-03-30    13F      USD
1  US.AAPL   苹果           计算机   3.398298e+11       7.7520            7.7624      -10565359         4.3088     -0.0719   2026-03-30    13F      USD
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get ARK Fund Holding

`get_ark_fund_holding(holding_type=None, cycle_type=None, sort_field=None, sort_dir=None, count=None, page=None)`

* **Description**

    Get ARK fund holdings, returning holding data for ARK ETFs, with support for viewing by holding/increase/decrease/open position/close position type, different time cycles, and multi-dimensional sorting.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    holding_type|[ArkHoldingType](./quote-market.md#2522)|Holding type, default holdings
    cycle_type|[ArkCycleType](./quote-market.md#8421)|Cycle type, default last 1 day (ignored when holdingType=holdings)
    sort_field|[ArkFundHoldingSortField](./quote-market.md#5175)|Sort field, default holding quantity
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 20
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.TSLA'`, some securities may be N/A)
        name|str|Name
        shares|int|Holding quantity
        shares_change|int|Holding quantity change
        market_value|float|Holding market value (USD)
        weight|float|Holding weight (%)
        weight_change|float|Holding weight change (%)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_ark_fund_holding(count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 2
  security                       name    shares  shares_change  market_value  weight  weight_change
0      N/A                        N/A  62494591       15631862  6.249459e+07    0.45           0.12
1  US.RXRX  Recursion Pharmaceuticals  31671298         -71280  1.007147e+08    0.73           0.01
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get ARK Stock Dynamic

`get_ark_stock_dynamic(security)`

* **Description**

    Get ARK stock trading dynamic, returning the latest trading activity information for a specified stock in ARK funds (consecutive same-direction trades, recent transactions, latest transaction, etc.).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    security|str|Stock code (e.g. `'US.TSLA'`) (required)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dict data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        dynamic_type|str|Dynamic type (see enum below)
        transaction_count|int|Number of transactions
        net_shares|int|Net traded shares
        last_transaction_time|str|Latest transaction time (yyyy-MM-dd)
        "CONSECUTIVE_SAME_DIRECTION"|Consecutive same-direction trades|
        "RECENT_TRANSACTION"|Recent transaction|
        "LAST_TRANSACTION"|Latest transaction|
        "NO_DYNAMIC"|No activity|

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_ark_stock_dynamic(security='US.TSLA')
if ret == RET_OK:
    for k, v in data.items():
        print(f"{k}: {v}")
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
dynamic_type: CONSECUTIVE_SAME_DIRECTION
transaction_count: 2
net_shares: 76041
last_transaction_time: 2026-06-22
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get ARK Active Transaction

`get_ark_active_transaction(holding_type=None, cycle_type=None, sort_field=None, sort_dir=None, count=None, page=None)`

* **Description**

    Get ARK active transaction aggregation, returning ARK fund active trading records (including change amount and change shares), with support for filtering by holding change type, cycle selection, and sorting.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    holding_type|[ArkActiveTransactionHoldingType](./quote-market.md#9747)|Holding change type, default increase holdings
    cycle_type|[ArkCycleType](./quote-market.md#8421)|Cycle type, default last 1 day
    sort_field|[ArkActiveTransactionSortField](./quote-market.md#8639)|Sort field, default change amount
    sort_dir|[RankSortDir](./quote-market.md#2129)|Sort direction, default descending
    count|int|Return count [1, 200], default 50
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.TSLA'`, some securities may be N/A)
        name|str|Name
        change_amount|float|Change amount (USD)
        change_shares|int|Change quantity (shares)

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_ark_active_transaction(count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 2
  security      name  change_amount  change_shares
0  US.AMZN       亚马逊      9631518.0          41141
1  US.PLTR  Palantir      9482340.0          81254
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Rating Change

`get_rating_change(market, change_type=None, count=None, page=None)`

* **Description**

    Get rating changes, returning US stock rating change records (upgrade/downgrade/initial rating), including institution name, target price changes and other information, with pagination support.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (US only) (required)
    change_type|[RatingChangeType](./quote-market.md#9727)|Rating change type ("UPGRADE"/"DOWNGRADE"/"NEW_RATING")
    count|int|Return count [1, 20], default 10
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.TSLA'`)
        name|str|Stock name
        rating|str|Current rating ("BUY"/"HOLD"/"SELL")
        last_rating|str|Previous rating ("BUY"/"HOLD"/"SELL")
        target_price|float|Current target price
        last_target_price|float|Previous target price
        change_type|str|Rating change type ("UPGRADE"/"DOWNGRADE"/"NEW_RATING")
        institution_name|str|Institution name
        recommendation_date|str|Recommendation date (yyyy-MM-dd)
        last_recommendation_date|str|Previous recommendation date (yyyy-MM-dd)
        "SELL"|Sell|
        "HOLD"|Hold|
        "BUY"|Buy|

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_rating_change(market=Market.US, count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 5904
  security  name rating last_rating  target_price  last_target_price change_type institution_name recommendation_date last_recommendation_date
0    US.MU  美光科技    BUY         BUY        1500.0              950.0     UPGRADE             美银证券          2026-06-23               2026-05-13
1  US.INTC   英特尔    BUY         BUY         160.0              135.0     UPGRADE             美银证券          2026-06-23               2026-06-11
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Industrial Chain List

`get_industrial_chain_list(market, keyword=None, count=None, page=None)`

* **Description**

    Get the industrial chain list, returning industrial chain information for the specified market (including chain type, market cap, number of constituent stocks, etc.), with support for keyword search and cursor-based pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (required)
    keyword|str|Search keyword
    count|int|Number of results [1, 50], default 20
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        chain_id|int|Industrial chain ID
        chain_type|str|Industrial chain type ("CHAIN"/"PARALLEL"/"UP_MID_DOWN")
        name|str|Industrial chain name
        detail|str|Detail description
        market_cap|float|Market cap
        stocks_num|int|Number of constituent stocks
        relation_security_list|list|Related stock code list
        "CHAIN"|Serial type|
        "PARALLEL"|Parallel type|
        "UP_MID_DOWN"|Upstream-midstream-downstream type|

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_industrial_chain_list(market=Market.US, count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 70
   chain_id   chain_type  name                                             detail    market_cap  stocks_num relation_security_list
0   9610020  UP_MID_DOWN    AI  AIGC（Artificial Intelligence Generated Content...  4.801784e+13         329     [US.NVDA, US.AAPL]
1   9610085  UP_MID_DOWN  商业航天                                                     2.590359e+12         155        [US.GE, US.RTX]
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Industrial Chain Detail

`get_industrial_chain_detail(chain_id)`

* **Description**

    Get industrial chain detail, returning the complete structural information of the specified industrial chain, including hierarchical node list and related news links.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    chain_id|int|Industrial chain ID

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dict data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        chain_id|int|Industrial chain ID
        chain_type|str|Industrial chain type ("CHAIN"/"PARALLEL"/"UP_MID_DOWN")
        name|str|Industrial chain name
        node_list|list[dict]|Node list (grouped by level)
        information_list|list[dict]|News link list
        node_id|int|Node ID
        parent_node_id|int|Parent node ID (root node is 0)
        layer|int|Node level (starting from 1)
        name|str|Node name
        plate_id|int|Associated industrial plate ID (N/A if none)
        title|str|News title
        url|str|News link

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_industrial_chain_detail(chain_id=9610020)
if ret == RET_OK:
    print(f"chain_id: {data['chain_id']}")
    print(f"chain_type: {data['chain_type']}")
    print(f"name: {data['name']}")
    print(f"node_list (first 2 items):")
    for node in data['node_list'][:2]:
        print(f"  {node}")
    print(f"information_list: {data['information_list']}")
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
chain_id: 9610020
chain_type: UP_MID_DOWN
name: AI
node_list (first 2 items):
  {'node_id': 1, 'parent_node_id': 'N/A', 'layer': 1, 'name': '基础建设层', 'plate_id': 'N/A'}
  {'node_id': 4, 'parent_node_id': 'N/A', 'layer': 1, 'name': '算法层', 'plate_id': 'N/A'}
information_list: []
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Industrial Chain By Plate

`get_industrial_chain_by_plate(plate_id)`

* **Description**

    Get industrial chains associated with a plate, returning the list of industrial chains associated with the specified industrial plate (including type, market cap, and number of constituent stocks).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    plate_id|int|Industrial plate ID (obtained from `get_industrial_chain_detail` node_list) (required)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>list</td>
            <td>When ret == RET_OK, returns list data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        chain_id|int|Industrial chain ID
        chain_type|str|Industrial chain type ("CHAIN"/"PARALLEL"/"UP_MID_DOWN")
        name|str|Industrial chain name
        market_cap|float|Market cap
        stocks_num|int|Number of constituent stocks
        "CHAIN"|Serial type|
        "PARALLEL"|Parallel type|
        "UP_MID_DOWN"|Upstream-midstream-downstream type|

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_industrial_chain_by_plate(plate_id=10010508)
if ret == RET_OK:
    for chain in data:
        print(chain)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
{'chain_id': 9610020, 'chain_type': 'UP_MID_DOWN', 'name': 'AI', 'market_cap': 26949823045632.0, 'stocks_num': 329}
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Industrial Plate Info

`get_industrial_plate_info(plate_id)`

* **Description**

    Get industrial plate info, returning the summary information of the specified industrial plate.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    plate_id|int|Industrial plate ID

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dict data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        plate_id|int|Industrial plate ID
        summary|str|Plate summary

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_industrial_plate_info(plate_id=10010508)
if ret == RET_OK:
    for k, v in data.items():
        print(f"{k}: {v}")
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
plate_id: 10010508
summary: N/A
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Industrial Plate Stock

`get_industrial_plate_stock(chain_id=None, plate_id=None, market_list=None,
                                            sort_field=None, ascend=None, count=None, page=None)`

* **Description**

    Get industrial plate constituent stocks, returning the stock list of the specified industrial plate, with support for market filtering, sorting, and pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    chain_id|int|Industrial chain ID (choose one with plate_id, plate_id takes priority)
    plate_id|int|Industrial plate ID (preferred)
    market_list|list[`Market`]|Market filter (supports HK/US/CN/JP/SG/MY), default all if not provided
    sort_field|[PlateStockSortField](./quote-market.md#6403)|Sort field, default market cap
    ascend|bool|Ascending True / Descending False, default False (descending)
    count|int|Per page count [1, 200], default 50
    page|str|Page cursor

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        security|str|Stock code (e.g. `'US.AAPL'`)
        name|str|Stock name

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_industrial_plate_stock(plate_id=10010508, count=2)
if ret == RET_OK:
    print(f'Total count: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total count: 111
  security name
0  US.NVDA  英伟达
1  US.AAPL   苹果
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts towards rate limiting
:::

---

# Get Heat Map Data

`get_heat_map_data(market, sort_field=None, ascend=None, count=None, page=None, plate_type=None)`

* **Description**

    Get heat map data, returning sector heat map information for a specified market (including change rate, market value, turnover, rise/fall counts, leading stocks, etc.), with support for multi-dimensional sorting and cursor pagination.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    market|[Market](./quote.md#456)|Market type (required)
    sort_field|[HeatMapSortField](./quote-market.md#6124)|Sort field, default change rate
    ascend|bool|True=ascending, False=descending, default descending
    count|int|Return count [1, 200], default 30
    page|str|Page cursor
    plate_type|[HeatMapPlateType](./quote-market.md#829)|Sector type, default industry sector

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        plate|str|Sector code (e.g. `'HK.BK1001'`)
        plate_name|str|Sector name
        cur_price|float|Latest price
        change_rate|float|Change rate (%)
        turnover|float|Turnover
        volume|int|Volume
        market_val|float|Market cap
        pe_avg|float|Average P/E ratio
        rise_count|int|Rise count
        fall_count|int|Fall count
        equal_count|int|Unchanged count
        leader_stock|str|Leading stock code
        description|str|Sector description

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data, next_page, all_count = quote_ctx.get_heat_map_data(market=Market.US, count=2)
if ret == RET_OK:
    print(f'Total sectors: {all_count}')
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
Total sectors: 145
         plate plate_name    cur_price  change_rate      turnover     volume    market_val  pe_avg  rise_count  fall_count  equal_count leader_stock description
0  US.LIST2496  人力资源与就业服务  1229.174414     4.717340  7.345543e+08  437599614  1.502404e+10  -6.112          15           3            2      US.ATLN         N/A
1  US.LIST2473         糖果  1696.630748     3.295289  1.178965e+09   14299774  1.176028e+11  49.691           4           1            0      US.RMCF         N/A
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Get Rise/Fall Distribution

`get_rise_fall_distribution(security=None, market=None)`

* **Description**

    Get rise/fall distribution, returning the distribution of rising and falling stocks by range for a specified plate or market, useful for understanding overall market movement patterns.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    security|str|Plate code (takes priority, e.g. `'HK.BK1001'`)
    market|[Market](./quote.md#456)|Market type (used when `security` is not provided)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns dict data</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Data format:
        Field|Type|Description
        :-|:-|:-
        plate|str|Plate code
        range_list|list[dict]|Rise/fall distribution range list
        type|str|Distribution type (string, see table below)
        left_border|int|Left boundary value
        right_border|int|Right boundary value
        stock_count|int|Number of stocks in range
        "RISE_LIMIT"|Limit up (A-share)|
        "POSITIVE_INFINITY"|(7%, +∞)|
        "NORMAL_RANGE"|Normal range|
        "NEGATIVE_INFINITY"|(-∞, -7%)|
        "FALL_LIMIT"|Limit down (A-share)|

* **Example**

```python
from futu import *

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_rise_fall_distribution(market=Market.US)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)

quote_ctx.close()
```

* **Output**

```
{'plate': 'US.USAALL', 'range_list': [{'type': 'NEGATIVE_INFINITY', 'left_border': 0, 'right_border': -7, 'stock_count': 817}, {'type': 'NORMAL_RANGE', 'left_border': -7, 'right_border': -5, 'stock_count': 581}, {'type': 'NORMAL_RANGE', 'left_border': 0, 'right_border': 3, 'stock_count': 4168}, {'type': 'NORMAL_RANGE', 'left_border': 0, 'right_border': 0, 'stock_count': 4310}, {'type': 'POSITIVE_INFINITY', 'left_border': 7, 'right_border': 0, 'stock_count': 416}]}
```

:::tip API Limits
- Maximum 60 requests within 30 seconds
- Only the first page of paginated requests counts toward rate limiting
:::

---

# Market Definitions

## ARK Active Transaction Holding Change Type

> **ArkActiveTransactionHoldingType**

* `INCREASE`

  Increase holding (default)

* `DECREASE`

  Decrease holding

* `NEW`

  Open position

* `SOLD_OUT`

  Close position

## ARK Active Transaction Sort Field

> **ArkActiveTransactionSortField**

* `CHANGE_AMOUNT`

  Change amount (default)

* `CHANGE_SHARES`

  Change shares

## ARK Cycle Type

> **ArkCycleType**

* `ONE_DAY`

  Last 1 day (default)

* `FIVE_DAY`

  Last 5 days

* `TEN_DAY`

  Last 10 days

* `THIRTY_DAY`

  Last 30 days

* `SIXTY_DAY`

  Last 60 days

## ARK Fund Holding Sort Field

> **ArkFundHoldingSortField**

* `SHARES`

  Holding quantity (default)

* `WEIGHT_CHANGE`

  Weight change

* `SHARES_CHANGE`

  Holding change

* `MARKET_VALUE`

  Market cap

* `WEIGHT`

  ETF weight

## ARK Holding Type

> **ArkHoldingType**

* `POSITION`

  Holding (default)

* `INCREASE`

  Increase holding

* `DECREASE`

  Decrease holding

* `NEW`

  Open position

* `SOLD_OUT`

  Close position

## Earnings Beat Time Range

> **BeatTerm**

* `LATEST`

  Latest period (default)

* `LATEST_QUARTER`

  Latest quarterly report

* `LATEST_HALF`

  Latest semi-annual report

* `LATEST_ANNUAL`

  Latest annual report

* `ALL`

  All (quarterly preferred if same time, latest period if different)

## Earnings Beat Type

> **BeatType**

* `EPS`

  Earnings per share

* `REVENUE`

  Revenue

* `EBIT`

  EBIT (Earnings before interest and taxes)

## Dividend Distribution Frequency Type

> **DistributionFrequency**

* `ANNUAL`

  Annual

* `SEMI_ANNUAL`

  Semi-annual

* `QUARTERLY`

  Quarterly

* `MONTHLY`

  Monthly

## Dividend Rank Sort Field

> **DividendRankSortField**

* `DIVIDEND_YIELD_TTM`

  Dividend yield TTM

* `AVG_DIVIDEND_YIELD_5Y`

  5-year average dividend yield

* `DISTRIBUTION_FREQUENCY`

  Distribution frequency

* `DIVIDEND_GROW_YEAR`

  Consecutive dividend growth years

* `DIVIDENDS_TTM`

  Dividends TTM

* `PAYOUT_RATIO_LFY`

  Dividend payout ratio LFY

* `PRICE`

  Price

* `MARKET_CAP`

  Market cap

* `CHANGE_RATE`

  Today's price change

* `CHANGE_AMOUNT`

  Today's price change amount

## Dividend Rank Type

> **DividendRankType**

* `HIGH_YIELD`

  High dividend yield

* `DIVIDEND_GROWTH`

  Dividend growth

## Earnings Beat Sort Field

> **EarningsBeatSortField**

* `BEAT_RATIO`

  Beat estimate ratio

* `EARNING_DAY_CHG`

  First-day gain after earnings

* `RELEASED_DATE`

  Publish time

* `ACTUAL`

  Actual value

* `ESTIMATE`

  Forecast value

* `YOY`

  Same period last year

* `YOY_GROWTH`

  Year-over-year growth rate

* `PE_TTM`

  P/E ratio TTM

* `DIVIDENDS_TTM`

  Dividend yield TTM

* `PRICE`

  Price

* `CHANGE_RATE`

  Today's price change

## Earnings Calendar Estimate Type

> **EarningsCalendarEstimateType**

* `EPS`

  Earnings per share (EPS GAAP)

* `REVENUE`

  Total revenue

* `EBIT`

  EBIT

## Earnings Calendar Publication Type

> **EarningsCalendarPubType**

* `REGULAR`

  Intraday (period unidentified)

* `BEFORE`

  Pre-market

* `AFTER`

  After-hours

## Earnings Calendar Sort Type

> **EarningsCalendarSortType**

* `HOT`

  Popular (default)

* `MARKET_CAP`

  Historical market cap

* `OPTION_VOLUME`

  Option volume (HK/US stocks only)

* `IV`

  Implied volatility (HK/US stocks only)

* `IV_RANK`

  IV rank (HK/US stocks only)

* `IV_PERCENTILE`

  IV percentile (HK/US stocks only)

* `RT_MARKET_CAP`

  Real-time market cap

## Earnings Calendar Stock List Type

> **EarningsCalendarStockListType**

* `WATCHLIST`

  Watchlist

* `POSITION`

  Position

* `SPECIAL`

  Special attention

## Economic Data Importance

> **EconomicImportance**

* `ALL`

  All (default)

* `LOW`

  One star (low)

* `MEDIUM`

  Two stars (medium)

* `HIGH`

  Three stars (high)

## Heat Map Plate Type

> **HeatMapPlateType**

* `INDUSTRY`

  Industry plate (default)

* `CONCEPT`

  Concept plate

* `THEME`

  Theme plate

## Heat Map Sort Field

> **HeatMapSortField**

* `CHANGE_RATE`

  Price change (default)

* `MARKET_VAL`

  Market cap

* `TURNOVER`

  Turnover

* `HOT`

  Popularity

## High Dividend SOE Sort Field

> **HighDividendSOESortField**

* `MARKET_CAP`

  Market cap (default)

* `DIVIDEND_YIELD_TTM`

  Dividend yield TTM

* `PB`

  P/B ratio

* `PE_TTM`

  P/E ratio TTM

* `PRICE`

  Last price

* `CHANGE_RATIO`

  Today's price change

## Hot List Sort Field

> **HotListSortField**

* `TRADE_HEAT`

  Trading popularity

* `SEARCH_HEAT`

  Search popularity

* `NEWS_HEAT`

  News popularity

* `AVERAGE_HEAT`

  Comprehensive popularity (default)

## Institution Holding Change Sort Field

> **InstitutionHoldingChangeSortField**

* `CHANGE_PCT`

  Change ratio (default)

* `CHANGE_SHARES`

  Change shares

* `HOLDING_DATE`

  Holding time

## Institution Holding Change Type

> **InstitutionHoldingChangeType**

* `NEW`

  Open position (default)

* `SOLD_OUT`

  Close position

* `INCREASE`

  Increase position

* `DECREASE`

  Reduce position

## Institution Holding List Sort Field

> **InstitutionHoldingListSortField**

* `HOLDING_VALUE`

  Holding market value (default)

* `HOLDING_PCT`

  Holding ratio (of total stock market cap)

* `LAST_HOLDING_PCT`

  Previous holding ratio

* `CHANGE_SHARES`

  Change shares

* `CHANGE_PCT`

  Change ratio

* `PORTFOLIO_PCT`

  Ratio of total institutional position

* `INDUSTRY`

  Industry

* `HOLDING_DATE`

  Holding time

## Institution List Sort Field

> **InstitutionListSortField**

* `POSITION_VALUE`

  Holding market value (default)

* `POSITION_VALUE_CHANGE`

  Position change

* `POSITION_COUNT`

  Holding shares

* `POSITION_COUNT_CHANGE`

  Holding shares change

## Macro Data Unit Type

> **MacroDataUnitType**

* `PERCENT`

  Percentage (%)

* `VALUE`

  Value

* `INDEX`

  Index

## Macro Economic Region

> **MacroRegion**

* `HK`

  Hong Kong

* `US`

  United States

* `JP`

  Japan

* `SG`

  Singapore

* `AU`

  Australia

* `CA`

  Canada

* `MY`

  Malaysia

* `CN`

  China (SH/SZ)

## Industry Chain Plate Stock Sort Field

> **PlateStockSortField**

* `CODE`

  Code

* `CHANGE_RATE`

  Price change

* `TURNOVER`

  Turnover

* `VOLUME`

  Volume

* `MARKET_VAL`

  Market cap (default)

## Price Filter Type

> **PriceFilter**

* `ALL`

  All (default)

* `LESS_THAN_1`

  Less than 1

* `BETWEEN_1_AND_10`

  Between 1~10

* `BETWEEN_10_AND_100`

  Between 10~100

* `GREATER_THAN_100`

  Greater than 100

* `NEAR_52_WEEK_HIGH`

  Near 52-week high

* `NEAR_52_WEEK_LOW`

  Near 52-week low

## Rank Period Type

> **RankPeriodType**

* `FIVE_MIN`

  5 minutes (default)

* `ONE_DAY`

  1 day

* `FIVE_DAY`

  5 days

* `TWENTY_DAY`

  20 days

* `SIXTY_DAY`

  60 days

* `ONE_TWENTY_DAY`

  120 days

* `TWO_FIFTY_DAY`

  250 days

* `YTD`

  Year-to-date

## Rank Sort Direction

> **RankSortDir**

* `DESCENDING`

  Descending (default)

* `ASCENDING`

  Ascending

## Rating Change Type

> **RatingChangeType**

* `UPGRADE`

  Rating upgrade (default)

* `DOWNGRADE`

  Rating downgrade

* `NEW_RATING`

  Initial rating

## Short Selling Sort Field

> **ShortSellingSortField**

* `SHORT_NUMBER_CHANGE`

  Short selling change volume (default)

* `SHORT_RATIO_CHANGE`

  Short selling change ratio

* `SHORT_NUMBER`

  Short selling volume

* `SHORT_RATIO`

  Short selling ratio

* `VOLUME`

  Volume

* `POSITION_VOLUME`

  Short position volume

* `POSITION_RATIO`

  Short position ratio

* `DAYS_TO_COVER`

  Days to cover

* `WEEK_AVG_VOLUME`

  Recent 1-week daily average volume

* `WEEK_AVG_SHORT_NUMBER`

  Recent 1-week daily average short selling volume

* `WEEK_AVG_SHORT_RATIO`

  Recent 1-week daily average short selling ratio

* `MONTH_AVG_VOLUME`

  Recent 1-month daily average volume

* `MONTH_AVG_SHORT_NUMBER`

  Recent 1-month daily average short selling volume

* `MONTH_AVG_SHORT_RATIO`

  Recent 1-month daily average short selling ratio

---

# Get Indicator List

`get_indicator_list(search_key='', lang_type=IndicatorLangType.NONE, search_mode=IndicatorSearchMode.PARTIAL)`

* **Description**

    Get the list of supported indicators. Supports filtering by keyword, indicator script language (MyLang / Python) and search mode (partial / exact).

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    search_key|str|Search keyword. Leave empty to return all indicators
    lang_type|[IndicatorLangType](./quote.md#7629)|Indicator script language. Leave empty or `NONE` to not filter by language
    search_mode|[IndicatorSearchMode](./quote.md#4663)|Search mode, default partial match

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>When ret == RET_OK, returns indicator list</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * DataFrame fields:

        Field|Type|Description
        :-|:-|:-
        short_name|str|Indicator short name, unique within the same language
        full_name|str|Indicator full name
        lang_type|[IndicatorLangType](./quote.md#7629)|Script language (MyLang / Python)
        inputs|list|Input parameter list, each item is an [IndicatorInputParam](./quote.md)
        outputs|list|Output parameter list, each item is an [IndicatorOutputParam](./quote.md)
        script|str|Script source code, only returned when `search_mode = Exact` and `search_key` is non-empty

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_indicator_list('MACD', IndicatorLangType.MyLang, IndicatorSearchMode.PARTIAL)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```
</content>
</invoke>

---

# Asynchronously Request Indicator Calculation

`request_indicator_calc_async(short_name, lang_type, code, kl_type, klines, num=None, input_params=None)`

* **Description**

    Asynchronously request indicator calculation. The API returns a `calc_id` immediately; the actual calculation result is delivered asynchronously through the [push-indicator-calc](./push-indicator-calc.md) callback, paired by `calc_id`.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    short_name|str|Indicator short name
    lang_type|[IndicatorLangType](./quote.md#7629)|Script language type
    code|str|Stock code, e.g. `HK.00700`
    kl_type|[KLType](./quote.md#66)|K-line type
    klines|pd.DataFrame or list[dict]|K-line data
    num|int or None|Use at most the first N K-lines; None means all K-lines
    input_params|list[dict] or None|Input parameter overrides (optional)

* **Return**

    <table>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>str</td>
            <td>When ret == RET_OK, returns the `calc_id` of the calculation task, used to pair with push results</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

* **Example**

```python
from moomoo import *
import time

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

class IndicatorCalcHandler(IndicatorCalcHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, content = super(IndicatorCalcHandler, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print('error:', content)
            return ret_code, content
        print('calc result:', content)
        return RET_OK, content

quote_ctx.set_handler(IndicatorCalcHandler())

ret, kl_data, _ = quote_ctx.request_history_kline('HK.00700', start='2024-01-01', end='2024-03-01', ktype=KLType.K_DAY)
if ret == RET_OK:
    ret, calc_id = quote_ctx.request_indicator_calc_async(
        'MACD', IndicatorLangType.MYLANG, 'HK.00700', KLType.K_DAY, kl_data)
    print('calc_id:', calc_id)

time.sleep(5)
quote_ctx.close()
```
if ret == RET_OK:
    print('calc_id:', calc_id)
else:
    print('error:', calc_id)
quote_ctx.close() # Remember to close the connection to avoid exhausting connection quota
```
</content>
</invoke>

---

# Indicator Async Calc Result Push

`on_recv_rsp(self, rsp_pb)`

* **Description**

    Indicator async calculation result push callback. The result is paired with the original request submitted via [request-indicator-calc](./request-indicator-calc.md) by `calc_id`. The client registers a handler (typically via `set_handler`) to passively receive the push.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_PushIndicatorCalc_pb2.Response|This parameter does not need to be processed directly in the derived class.

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800">RET_CODE</a></td>
            <td>API call result</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>When ret == RET_OK, returns the indicator calculation result</td>
        </tr>
        <tr>
            <td>str</td>
            <td>When ret != RET_OK, returns error description</td>
        </tr>
    </table>

    * Result fields:

        Field|Type|Description
        :-|:-|:-
        calc_id|str|Calculation task ID, matches the value returned by `request_indicator_calc_async`
        outputs|list|Output line metadata, each item is an [IndicatorOutputParam](./quote.md)
        output_rows|list|Calculation result in time order, each row contains `time` and `values` (one value per output)

* **Example**

```python
import time
from moomoo import *
class IndicatorCalcTest(IndicatorCalcHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(IndicatorCalcTest, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("IndicatorCalcTest: error, msg: %s" % data)
            return RET_ERROR, data
        print("IndicatorCalcTest ", data)
        return RET_OK, data

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = IndicatorCalcTest()
quote_ctx.set_handler(handler)
ret, kl_data, _ = quote_ctx.request_history_kline('US.AAPL', start='2024-01-01', end='2024-06-01', ktype=KLType.K_DAY)
if ret == RET_OK:
    quote_ctx.request_indicator_calc_async('MACD', IndicatorLangType.MYLANG, 'US.AAPL', KLType.K_DAY, kl_data)
time.sleep(15)
quote_ctx.close()
```

:::tip Tips
* This interface provides the function of continuously receiving pushed indicator calculation results. To trigger a calculation, call [request-indicator-calc](./request-indicator-calc.md). Each push is paired with the original request by `calcId`.
:::
</content>
</invoke>

---

# Get Details of Historical Candlestick Quota

`get_history_kl_quota(get_detail=False)`

* **Description**

    Get usage details of historical candlestick quota

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    get_detail|bool|Whether to return the detailed record of historical candlestick pulled.  (True: return. False: not return.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>If ret == RET_OK, historical candlestick quota is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Historical candlestick quota format as follows: 
        Field|Type|Description
        :-|:-|:-
        used_quota|int|Used quota.  (How many stocks have been downloaded in the current period.)
        remain_quota|int|Remaining quota.
        detail_list|list|Detailed records of historical candlestick data pulled, including stock code and pulling time.  (Data type of elements in the list is dict.)

        - detail_list, the data column format is as follows
            Field|Type|Description
            :-|:-|:-
            code|str|Stock code.
            name|str|Stock name.
            request_time|str|The time string of the last pull.  (yyyy-MM-dd HH:mm:ss.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_history_kl_quota(get_detail=True)  # Setting True means that you need to return the detailed record of historical candlestick pulled
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
(2, 98,  {'code': 'HK.00123', 'name': 'YUEXIU PROPERTY', 'request_time': '2023-06-20 19:59:00'}, {'code': 'HK.00700', 'name': 'TENCENT', 'request_time': '2023-07-19 16:44:14'}])
```


:::tip Interface Restrictions
* We will issue historical candlestick quotas based on the assets and tradings of your account. Therefore, you can only obtain historical candlestick data for a limited number of stocks within 7 days. For specific rules, please refer to [Subscription Quota & Historical Candlestick Quota](../intro/authority.md#9123).
* The historical candlestick quota you consume on that day will be automatically released after 7 days.
:::

---

# Set Price Reminder

`set_price_reminder(code, op, key=None, reminder_type=None, reminder_freq=None, value=None, note=None, reminder_session_list=NONE)`

* **Description**

    Add, delete, modify, enable, and disable price reminders for specified stocks

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Stock code
    op|[SetPriceReminderOp](./quote.md#8810)|Operation type.
    key|int|Identification, do not need to fill in the case of adding all or deleting all.
    reminder_type|[PriceReminderType](./quote.md#3793)|The type of price reminder, this input parameter will be ignored when delete, enable, or disable.
    reminder_freq|[PriceReminderFreq](./quote.md#9918)|The frequency of price reminder, this input parameter will be ignored when delete, enabled, or disable.
    value|float|Reminder value, the input parameter will be ignored when delete, enable, or disable.  (3 decimal place accuracy, the excess part is discarded.)
    note|str|The note set by the user, note supports no more than 20 Chinese characters, the input parameter will be ignored when delete, enable, or disable.
    reminder_session_list|list|The session for US stocks price reminder, this input parameter will be ignored when delete, enable, or disable.  (- The parameter type in list is [PriceReminderMarketStatus](./quote.md#6578).
  - The default price reminder session for US stocks is pre/post+RTH.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">key</td>
            <td>int</td>
            <td>If ret == RET_OK, The price reminder key of the operation is returned. When deleting all reminders of a specific stock, 0 is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>


* **Example**

```python
from moomoo import *
import time
class PriceReminderTest(PriceReminderHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, content = super(PriceReminderTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("PriceReminderTest: error, msg: %s" % content)
            return RET_ERROR, content
        print("PriceReminderTest ", content)
        return RET_OK, content
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = PriceReminderTest()
quote_ctx.set_handler(handler)
ret, data = quote_ctx.get_market_snapshot(['US.AAPL'])
if ret == RET_OK:
    bid_price = data['bid_price'][0] # Get real-time bid price
    ask_price = data['ask_price'][0] # Get real-time selling price
    # Set a reminder for AAPL(24H) when the selling price is lower than (ask_price-1)
    ret_ask, ask_data = quote_ctx.set_price_reminder(code='US.AAPL', op=SetPriceReminderOp.ADD, key=None, reminder_type=PriceReminderTypeASK_PRICE_DOWN, reminder_freq=PriceReminderFreq.ALWAYS, value=(ask_price-1), note='123', reminder_session_list=[PriceReminderMarketStatus.US_PRE, PriceReminderMarketStatus.OPEN, PriceReminderMarketStatus.US_AFTER, PriceReminderMarketStatus.US_OVERNIGHT])
    if ret_ask == RET_OK:
        print('When the selling price is lower than (ask_price-1), remind that the setting is successful:', ask_data)
    else:
        print('error:', ask_data)
    # Set a reminder for AAPL(24H) when the bid price is higher than (bid_price+1)
    ret_bid, bid_data = quote_ctx.set_price_reminder(code='US.AAPL', op=SetPriceReminderOp.ADD, key=None, reminder_type=PriceReminderType.BID_PRICE_UP, reminder_freq=PriceReminderFreq.ALWAYS, value=(bid_price+1), note='456', reminder_session_list=[PriceReminderMarketStatus.US_PRE, PriceReminderMarketStatus.OPEN, PriceReminderMarketStatus.US_AFTER, PriceReminderMarketStatus.US_OVERNIGHT])
    if ret_bid == RET_OK:
        print('When the bid price is higher than (bid_price+1), the reminder is set successfully: ', bid_data)
    else:
        print('error:', bid_data)
time.sleep(15)
quote_ctx.close()
```

* **Output**

```python
When the selling price is lower than (ask_price-1), the reminder is set successfully: 158815356110052101
When the bid price is higher than (bid_price+1), the reminder is set successfully: 158815356129980801
```

:::tip Tips
* Trading volume in API is based on shares. A-shares are shown in lots in moomoo Client.
* The type of price alert has minimum precision, as follows:

    TURNOVER_UP: The minimum precision of the turnover is 10 (Yuan, Hong Kong dollar, US dollar). The value passed in will be automatically rounded down to an integer multiple of the minimum precision. If you set 00700 transaction volume 102 yuan reminder, you will get 00700 transaction volume 100 yuan reminder. After setting; if you set 00700 transaction volume 8 yuan reminder, you will get 00700 transaction volume 0 yuan reminder after setting.

    VOLUME_UP: The minimum accuracy of A-share trading volume is 1000 shares, and the minimum accuracy of other market stock trading volume is 10 shares. The value passed in will be automatically rounded down to an integer multiple of the minimum precision.

    BID_VOL_UP, ASK_VOL_UP: The minimum precision for buying and selling of A-shares is 100 shares. The value passed in will be automatically rounded down to an integer multiple of the minimum precision.

    The precision of the remaining price alert types supports up to 3 decimal places
:::

:::tip Interface Limitations
* A maximum of 60 requests per 30 seconds
* The upper limit of reminders that can be set for each type of each stock is 10
:::

---

# Get Price Reminder List

`get_price_reminder(code=None, market=None)`

* **Description**

    Get a list of price reminders set for the specified stock or market

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Specified stock code. 
    market|[Market](./quote.md#456)|Specified market type.  (Note that either Shanghai or Shenzhen will be regarded as the A-share market.)
    Note: Choose either code or market, and code takes precedence if both exist.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, price reminder data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Price reminder data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        key|int|Identification, used to modify the price reminder.
        reminder_type|[PriceReminderType](./quote.md#3793)|The type of price reminder.
        reminder_freq|[PriceReminderFreq](./quote.md#9918)|The frequency of price reminder.
        value|float|Remind value.
        enable|bool|Whether to enable.
        note|str|Note.  (Note supports no more than 20 Chinese characters.)
        reminder_session_list|list|Price reminder session list for US stocks  (The parameter type in list is [PriceReminderMarketStatus](./quote.md#6578).)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_price_reminder(code='US.AAPL')
if ret == RET_OK:
    print(data)
    print(data['key'].values.tolist())   # Convert to list
else:
    print('error:', data)
print('******************************************')
ret, data = quote_ctx.get_price_reminder(code=None, market=Market.US)
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the price remind list is not empty
        print(data['code'][0])    # Take the first stock code
        print(data['code'].values.tolist())   # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
code name                  key   reminder_type reminder_freq   value  enable note                   reminder_session_list
0  US.AAPL   APPLE  1744021708234288125    BID_PRICE_UP        ALWAYS  184.37    True  456                              [US_AFTER]
1  US.AAPL   APPLE  1744022257052794489    BID_PRICE_UP        ALWAYS  185.50    True  456  [OPEN, US_PRE, US_AFTER, US_OVERNIGHT]
2  US.AAPL   APPLE  1744021708211891867  ASK_PRICE_DOWN        ALWAYS  182.54    True  123                              [US_AFTER]
3  US.AAPL   APPLE  1744022257023211123  ASK_PRICE_DOWN        ALWAYS  183.70    True  123  [OPEN, US_PRE, US_AFTER, US_OVERNIGHT]
[1744021708234288125, 1744022257052794489, 1744021708211891867, 1744022257023211123]
******************************************
      code name                  key   reminder_type reminder_freq   value  enable note                   reminder_session_list
0  US.AAPL   APPLE  1744021708234288125    BID_PRICE_UP        ALWAYS  184.37    True  456                              [US_AFTER]
1  US.AAPL   APPLE  1744022257052794489    BID_PRICE_UP        ALWAYS  185.50    True  456  [OPEN, US_PRE, US_AFTER, US_OVERNIGHT]
2  US.AAPL   APPLE  1744021708211891867  ASK_PRICE_DOWN        ALWAYS  182.54    True  123                              [US_AFTER]
3  US.AAPL   APPLE  1744022257023211123  ASK_PRICE_DOWN        ALWAYS  183.70    True  123  [OPEN, US_PRE, US_AFTER, US_OVERNIGHT]
4  US.NVDA  NVIDIA  1739697581665326308      PRICE_DOWN        ALWAYS  102.00    True       [OPEN, US_PRE, US_AFTER, US_OVERNIGHT]
US.AAPL
['US.AAPL', 'US.AAPL', 'US.AAPL', 'US.AAPL', 'US.NVDA']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Get The Watchlist

`get_user_security(group_name)`

* **Description**

    Get a list of a specified group from watchlist

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    group_name|str|The name of the specified group from watchlist.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, watchlist is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Watchlist data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        lot_size|int|Number of shares per lot, number of shares per contract for options, contract multiplier for futures.
        stock_type|[SecurityType](./quote.md#9767)|Stock type.
        stock_child_type|[WrtType](./quote.md#2421)|Warrant type.
        stock_owner|str|The code of the underlying stock to which the warrant belongs, or the code of the underlying stock of the option.
        option_type|[OptionType](./quote.md#9598)|Option type.
        strike_time|str|The option exercise date.  (Format: yyyy-MM-dd
The default of HK stock market and A-share market is Beijing time, while that of US stock market is US Eastern time.)
        strike_price|float|Option strike price.
        suspension|bool|Whether the option is suspended.  (True: suspension)
        listing_date|str|Listing date.  (Format: yyyy-MM-dd)
        stock_id|int|Stock ID.
        delisting|bool|Whether is delisted.
        main_contract|bool|Whether is future main contract.
        last_trade_time|str|Last trading time.  (Main, current month and next month futures do not have this field.)

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_user_security("A")
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the user security list is not empty
        print(data['code'][0]) # Take the first stock code
        print(data['code'].values.tolist()) # Convert to list
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
    code    name  lot_size stock_type stock_child_type stock_owner option_type strike_time strike_price suspension listing_date        stock_id  delisting  main_contract last_trade_time
0  HK.HSImain  HSI Future Main(NOV0)        50     FUTURE              N/A                                              N/A        N/A                     71000662      False           True                
1  HK.00700    Tencent Holdings       100      STOCK              N/A                                              N/A        N/A   2004-06-16  54047868453564      False          False                
HK.HSImain
['HK.HSImain', 'HK.00700']
```

:::tip Tips
The corresponding Chinese and English names of the system group are as follows
    
Chinese|English
:-|:-|:-
全部|All
沪深|CN
港股|HK
美股|US
期权|Options
港股期权|HK options
美股期权|US options
特别关注|Starred
期货|Futures
:::

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* Does not support position (Positions), fund treasure (Mutual Fund), foreign exchange (Forex) group query
:::

---

# Get Groups From Watchlist

`get_user_security_group(group_type = UserSecurityGroupType.ALL)`

* **Description**

    Get a list of groups from the user watchlist

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    group_type|[UserSecurityGroupType](./quote.md#8561)|Group type.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, group data of watchlist is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Group data of watchlist format as follows: 
        Field|Type|Description
        :-|:-|:-
        group_name|str|Group name.
        group_type|[UserSecurityGroupType](./quote.md#8561)|Group type.

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.get_user_security_group(group_type = UserSecurityGroupType.ALL)
if ret == RET_OK:
    print(data)
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
        group_name group_type
0          Options     SYSTEM
..         ...        ...
12          C     CUSTOM

[13 rows x 2 columns]
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
:::

---

# Modify the Watchlist

`modify_user_security(group_name, op, code_list)`

* **Description**

    Modify the specific group from the watchlist (you cannot modify the system group)

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    group_name|str|The name of the group from the watchlist that needs to be modified.
    op|[ModifyUserSecurityOp](./quote.md#5843)|Operation type.
    code_list|list|Stock list.  (Data type of elements in the list is str.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">msg</td>
            <td rowspan="2">str</td>
            <td>If ret == RET_OK, "success" is returned.</td>
        </tr>
        <tr>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>


* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

ret, data = quote_ctx.modify_user_security("A", ModifyUserSecurityOp.ADD, ['HK.00700'])
if ret == RET_OK:
    print(data) # Return success
else:
    print('error:', data)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
success
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds
* You can only modify custom groups, not the system group
* There is an upper limit on the number of "all" watchlist: 500 for untraded customers and 2000 for traded clients (when adding stocks to other groups, the "all" watchlist will also increase synchronously)
* If there are multiple groups with a same name, the first group will be operated
:::

---

# Price Reminder Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    The price reminder notification callback, asynchronously handles the notification push that has been set to the price reminder.
    After receiving the real-time price notification, it will call back to this function. You need to override on_recv_rsp in the derived class.


* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Qot_UpdatePriceReminder_pb2.Response|This parameter does not need to be processed directly in the derived class.


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>dict</td>
            <td>If ret == RET_OK, price reminder is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Price reminder format as follows: 
        Field|Type|Description
        :-|:-|:-
        code|str|Stock code.
        name|str|Stock name.
        price|float|Current price.
        change_rate|str|Current change rate.
        market_status|[PriceReminderMarketStatus](./quote.md#6578)|The time period for triggering.
        content|str|Text content of price reminder.
        note|str|Note.  (Note supports no more than 20 Chinese characters.)
        key|int|Price reminder identification.
        reminder_type|[PriceReminderType](./quote.md#3793)|The type of price reminder.
        set_value|float|The reminder value set by the user.
        cur_value|float|The value when the reminder was triggered.

* **Example**

```python
import time
from moomoo import *

class PriceReminderTest(PriceReminderHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, content = super(PriceReminderTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("PriceReminderTest: error, msg: %s" % content)
            return RET_ERROR, content
        print("PriceReminderTest ", content) # PriceReminderTest's own processing logic
        return RET_OK, content
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = PriceReminderTest()
quote_ctx.set_handler(handler) # Set price reminder notification callback
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current connection, OpenD will automatically cancel the corresponding type of subscription for the corresponding stock after 1 minute
```

* **Output**

```python
PriceReminderTest  {'code': 'US.AAPL', 'name': 'APPLE', 'price': 185.750, 'change_rate': 0.11, 'market_status': 'US_PRE', 'content': '买一价高于185.500', 'note': '', 'key': 1744022257052794489, 'reminder_type': 'BID_PRICE_UP', 'set_value': 185.500, 'cur_value': 185.750}
```

:::tip Tips
* This interface provides the function of continuously obtaining pushed data. If you need to obtain real-time data at one time, please refer to the [Get Price Reminder List](./get-price-reminder.md) API.
* For the difference between get real-time data and real-time data callback, please refer to [How to Get Real-time Quotes Through Subscription Interface](../qa/quote.md#5505) API.
:::

---

# Quotation Definitions

## Cumulative Filter Properties

> **StockField**

* `NONE`

  unknown

* `CHANGE_RATE`

  Yield  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-10.2, 20.4])

* `AMPLITUDE`

  Amplitude  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [0.5, 20.6])

* `VOLUME`

  Average daily trading volume  (- 0 decimal place accuracy, the excess part is discarded.
  - For example, a range of [2000, 70000])

* `TURNOVER`

  Average daily turnover  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1400, 890000])

* `TURNOVER_RATE`

  Turnover rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [2, 30])

## Asset Types

> **AssetClass**

* `UNKNOW`

  Unknown

* `STOCK`

  Stocks

* `BOND`

  Bonds

* `COMMODITY`

  Commodities

* `CURRENCY_MARKET`

  Currency markets

* `FUTURE`

  Futures

* `SWAP`

  Swaps

## Corporate Action


## Dark Disk Status

> **DarkStatus**

* `NONE`

  No grey market trading

* `TRADING`

  Ongoing grey market trading

* `END`

  Grey market trading finished

## Financial Filter Properties

> **StockField**

* `NONE`

  unknown

* `NET_PROFIT`

  Net profit  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [100000000, 2500000000])

* `NET_PROFIX_GROWTH`

  Net profit growth rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-10, 300])


* `SUM_OF_BUSINESS`

  Operating income  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [100000000, 6400000000]) 

* `SUM_OF_BUSINESS_GROWTH`

  Year-on-year growth rate of operating income  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-5, 200])

* `NET_PROFIT_RATE`

  Net profit rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 113])

* `GROSS_PROFIT_RATE`

  Gross profit margin  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [4, 65])
* `DEBT_ASSET_RATE`

  Asset-liability ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [5, 470])

* `RETURN_ON_EQUITY_RATE`

  Return on equity  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [20, 230])

* `ROIC`

  Return on invested capital  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `ROA_TTM`

  Return on assets TTM  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `EBIT_TTM`

  Earnings before interest and tax TTM  (- unit: yuan.
  - Only applicable to annual reports.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `EBITDA`

  Earnings before interest, tax, depreciation and amortization  (- unit: yuan. 
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `OPERATING_MARGIN_TTM`

  Operating profit margin TTM  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `EBIT_MARGIN`

  EBIT margin  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `EBITDA_MARGIN `

  EBITDA margin  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `FINANCIAL_COST_RATE`

  Financial cost rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `OPERATING_PROFIT_TTM `

  Operating profit TTM  (- unit: yuan.
  - Only applicable to annual reports.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `SHAREHOLDER_NET_PROFIT_TTM`

  Net profit attributable to the parent company  (- unit: yuan.
  - Only applicable to annual reports.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `NET_PROFIT_CASH_COVER_TTM`

  The proportion of cash income in profit  (- This field is in percentage form, so 20 is equivalent to 20%. 
  - Only applicable to annual reports.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1.0, 60.0]) 

* `CURRENT_RATIO`

  Current ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [100, 250])

* `QUICK_RATIO`

  Quick ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [100, 250])

* `CURRENT_ASSET_RATIO`

  Liquidity rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 100])

* `CURRENT_DEBT_RATIO`

  Current debt ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 100])

* `EQUITY_MULTIPLIER`

  Equity multiplier  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [100, 180])

* `PROPERTY_RATIO`

  Equity ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [50, 100])

* `CASH_AND_CASH_EQUIVALENTS`

  Cash and cash equivalent  (- unit: yuan.
  - 3 decimal place accuracy, the excess part is discarded.
  -  For example, a range of [1000000000, 1000000000])

* `TOTAL_ASSET_TURNOVER`

  Total asset turnover rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [50, 100])

* `FIXED_ASSET_TURNOVER`

  Fixed asset turnover rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [50, 100])

* `INVENTORY_TURNOVER`

  Inventory turnover rate  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [50, 100])

* `OPERATING_CASH_FLOW_TTM`

  Operating cash flow TTM  (- unit: yuan.
  - Only applicable to annual reports.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `ACCOUNTS_RECEIVABLE`

  Net accounts receivable  (- unit: yuan.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `EBIT_GROWTH_RATE`

  Year-on-year growth rate of EBIT  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `OPERATING_PROFIT_GROWTH_RATE`

  Year-on-year growth rate of operating profit  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `TOTAL_ASSETS_GROWTH_RATE`

  Year-on-year growth rate of total assets  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `PROFIT_TO_SHAREHOLDERS_GROWTH_RATE`

  Year-on-year growth rate of net profit attributed to parent company owner  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `PROFIT_BEFORE_TAX_GROWTH_RATE`

  Year-on-year growth rate of total profit  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `EPS_GROWTH_RATE`

  Year-on-year growth rate of EPS  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `ROE_GROWTH_RATE`

  Year-on-year growth rate of ROE  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `ROIC_GROWTH_RATE`

  Year-on-year growth rate of ROIC  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `NOCF_GROWTH_RATE`

  Year-on-year growth rate of operating cash flow  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `NOCF_PER_SHARE_GROWTH_RATE`

  Year-on-year growth rate of operating cash flow per share  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [1.0, 10.0])

* `OPERATING_REVENUE_CASH_COVER`

  Operating cash cover ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 100])

* `OPERATING_PROFIT_TO_TOTAL_PROFIT`

  Operating profit ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 100])

* `BASIC_EPS`

  Basic earnings per share  (- 3 decimal place accuracy, the excess part is discarded.
  - unit: yuan.
  - For example, a range of [0.1, 10])
  
* `DILUTED_EPS`

  Diluted earnings per share  (- 3 decimal place accuracy, the excess part is discarded.
  - unit: yuan.
  - For example, a range of [0.1, 10])

* `NOCF_PER_SHARE`

  Net operating cash flow per share  (- 3 decimal place accuracy, the excess part is discarded.
  - unit: yuan.
  - For example, a range of [0.1, 10])

## Financial Filter Properties Period

> **FinancialQuarter**

* `NONE`

  unknown

* `ANNUAL`

  annual report

* `FIRST_QUARTER`

  First quarter report

* `INTERIM`

  Interim report

* `THIRD_QUARTER`

  Third quarter report

* `MOST_RECENT_QUARTER`

  Latest quarter report

## Custom indicator attributes

> **StockField**

* `NONE`

  Unknown

* `PRICE`

  latest price

* `MA5`

  Simple moving average

* `MA5`

  5-day simple moving average (Not recommended)

* `MA10`

  10-day simple moving average (Not recommended)

* `MA20`

  20-day simple moving average (Not recommended)

* `MA30`

  30-day simple moving average (Not recommended)

* `MA60`

  60-day simple moving average (Not recommended)

* `MA120`

  120-day simple moving average (Not recommended)

* `MA250`

  250-day simple moving average (Not recommended)

* `RSI`

  RSI  (The default value of the indicator parameter is [12].)

* `EMA`

  Exponential moving average

* `EMA5`

  5-day exponential moving average (Not recommended)

* `EMA10`

  10-day exponential moving average (Not recommended)

* `EMA20`

  20-day exponential moving average (Not recommended)

* `EMA30`

  30-day exponential moving average (Not recommended)

* `EMA60`

  60-day exponential moving average (Not recommended)

* `EMA120`

  120-day exponential moving average (Not recommended)

* `EMA250`

  250-day exponential moving average (Not recommended)

* `KDJ_K`

  K value of KDJ indicator  (Indicator parameters need to be passed according to KDJ. If not passed, the default value is [9,3,3].)

* `KDJ_D`

  D value of KDJ indicator  (Indicator parameters need to be passed according to KDJ. If not passed, the default value is [9,3,3].)

* `KDJ_J`

  J value of KDJ indicator  (Indicator parameters need to be passed according to KDJ. If not passed, the default value is [9,3,3].)

* `MACD_DIFF`

  DIFF value of MACD indicator  (Indicator parameters need to be passed according to MACD. If not passed, the default value is [12,26,9].)

* `MACD_DEA`

  DEA value of MACD indicator  (Indicator parameters need to be passed according to MACD. If not passed, the default value is [12,26,9].)

* `MACD`

  MACD value of MACD indicator  (Indicator parameters need to be passed according to MACD. If not passed, the default value is [12,26,9].)

* `BOLL_UPPER`

  UPPER value of BOLL indicator  (Indicator parameters need to be passed according to BOLL. If not passed, the default value is [20,2].)

* `BOLL_MIDDLER`

  MIDDLER value of BOLL indicator  (Indicator parameters need to be passed according to BOLL. If not passed, the default value is [20,2].)

* `BOLL_LOWER`

  LOWER value of BOLL indicator  (Indicator parameters need to be passed according to BOLL. If not passed, the default value is [20,2].)

* `VALUE`

  Custom value (stock_field1 does not support this field)

## Indicator language type

> **IndicatorLangType**

* `UNKNOWN`

  No filter

* `MYLANG`

  MyLang

* `PYTHON`

  Python

## Indicator search mode

> **IndicatorSearchMode**

* `PARTIAL`

  Partial match (default)

* `EXACT`

  Exact match; also returns script field

## Indicator parameter value type

Possible values for the type field in indicator input value dict.

## Indicator shape

When type is SHAPE, value is the enum name string below.

## Indicator line type

When type is LINE, value is the enum name string below.

## Indicator parameter value

Indicator input value dict maps to this Protobuf message; SDK converts to Python values.

## Indicator input parameter

Structure of inputs elements returned by [get_indicator_list](./get-indicator-list.md).

## Indicator output parameter

Metadata for one output line; matches outputs elements in [push-indicator-calc](./push-indicator-calc.md) callback.

## Relative position

> **RelativePosition**

* `NONE`

  Unknown

* `MORE`

  Stock_field1 is greater than stock_field2

* `LESS`

  Stock_field1 is less than stock_field2

* `CROSS_UP`

  Stock_field1 cross over stock_field2

* `CROSS_DOWN`

  Stock_field1 cross below stock_field2

## Pattern attributes

> **PatternField**

* `NONE`

  未知

* `MA_ALIGNMENT_LONG`

  MA bullish alignment (MA5 > MA10 > MA20 > MA30 > MA60 for two consecutive days, and the closing price of the day is greater than the closing price of the previous day)

* `MA_ALIGNMENT_SHORT`

  MA bearish alignment (MA5 < MA10 < MA20 < MA30 < MA60 for two consecutive days, and the closing price of the day is less than the closing price of the previous day)

* `EMA_ALIGNMENT_LONG`

  EMA bullish alignment (EMA5 > EMA10 > EMA20 > EMA30 > EMA60 for two consecutive days, and the closing price of the day is greater than the closing price of the previous day)

* `EMA_ALIGNMENT_SHORT`

  EMA bearish alignment (EMA5 < EMA10 < EMA20 < EMA30 < MA60 for two consecutive days, and the closing price of the day is less than the closing price of the previous day)

* `RSI_GOLD_CROSS_LOW`

  RSI low golden cross (short-term RSI crosses over long-term RSI below 50 (short-term RSI of the previous day is less than long-term RSI, short-term RSI of the current day is greater than long-term RSI))

* `RSI_DEATH_CROSS_HIGH`

  RSI high dead cross (short-term RSI crosses below long-term RSI above 50 (short-term RSI of the previous day is greater than long-term RSI, short-term RSI of the current day is less than long-term RSI))

* `RSI_TOP_DIVERGENCE`

  RSI top divergence (two adjacent candlestick peaks, the CLOSE of the later peak > the CLOSE of the earlier peak, the RSI12 value of the later peak < the RSI12 value of the earlier peak)

* `RSI_BOTTOM_DIVERGENCE`

  RSI bottom divergence (two adjacent candlestick troughs, the CLOSE of the later trough < the CLOSE of the earlier trough, the RSI12 value of the later trough > the RSI12 value of the earlier trough)

* `KDJ_GOLD_CROSS_LOW`

  KDJ low golden cross (D value is less than or equal to 30, and the K value of the previous day is less than the D value, and the K value of the day is greater than the D value)

* `KDJ_DEATH_CROSS_HIGH`

  KDJ high death cross (D value is greater than or equal to 70, and the K value of the previous day is greater than the D value, and the K value of the day is less than the D value)

* `KDJ_TOP_DIVERGENCE`

  KDJ top divergence (two adjacent candlestick peaks, the CLOSE of the later peak > the CLOSE of the earlier peak, the J value of the later peak < the J value of the earlier peak)

* `KDJ_BOTTOM_DIVERGENCE`

  KDJ bottom divergence (two adjacent candlestick troughs, the CLOSE of the later trough < the CLOSE of the earlier trough, the J value of the later trough > the J value of the earlier trough)

* `MACD_GOLD_CROSS_LOW`

  MACD golden cross (DIFF crosses over DEA ​​(DIFF is less than DEA of the previous day, and DIFF is greater than DEA of the current day))

* `MACD_DEATH_CROSS_HIGH`

  MACD dead cross (DIFF crosses below DEA (DIFF is greater than DEA of the previous day, and DIFF is less than DEA of the current day))

* `MACD_TOP_DIVERGENCE`

  MACD top divergence (two adjacent candlestick peaks, the CLOSE of the later peak > the CLOSE of the earlier peak, the MACD value of the later peak < the MACD value of the earlier peak)

* `MACD_BOTTOM_DIVERGENCE`

  MACD bottom deviation (two adjacent candlestick troughs, the CLOSE of the later trough < the CLOSE of the earlier trough, the MACD value of the later trough > the MACD value of the earlier trough)

* `BOLL_BREAK_UPPER`

  Break up bollinger upper bound (the stock price of the previous day was lower than the upper bound, and the stock price of the current day is greater than the upper bound)

* `BOLL_BREAK_LOWER`

  Break up bollinger lower bound (the stock price of the previous day was greater than the lower bound, and the stock price of the current day is less than the lower bound)

* `BOLL_CROSS_MIDDLE_UP`

  Cross over bollinger mid line (the stock price of the previous day was lower than the mid line, and the stock price of the current day is greater than the mid line)

* `BOLL_CROSS_MIDDLE_DOWN`

  Cross below bollinger mid line (the stock price of the previous day was greater than the mid line, and the stock price of the current day is less than the mid line)

## Watchlist Group Type

> **UserSecurityGroupType**

* `NONE`

  unknown

* `CUSTOM`

  Custom groups

* `SYSTEM`

  System groups

* `ALL`

  All groups

## Index Option Category

> **IndexOptionType**

* `NONE`

  unknown

* `NORMAL`

  Ordinary index option

* `SMALL`

  Small Index Options

## Listing Time

> **IpoPeriod**

* `NONE`

  unknown

* `TODAY`

  Listed today

* `TOMORROW`

  To be listed tomorrow

* `NEXTWEEK`

  To be listed next week

* `LASTWEEK`

  Has been listed last week

* `LASTMONTH`

  Has been listed last month

## Warrant Issuer

> **Issuer**

* `UNKNOW`

  unknown

* `SG`

  Societe Generale

* `BP`

  BNP Paribas

* `CS`

  Credit Suisse

* `CT`

  Citi Bank

* `EA`

  The Bank of East Aisa

* `GS`

  Goldman Sachs

* `HS`

  HSBC

* `JP`

  JPMorgan Chase

* `MB`

  Macquarie Bank

* `SC`

  Standard Chartered Bank

* `UB`

  Union Bank of Switzerland

* `BI`

  Bank of China

* `DB`

  Deutsche Bank

* `DC`

  Daiwa Bank

* `ML`

  Merrill Lynch

* `NM`

  Nomura Bank

* `RB`

  Rabobank

* `RS`

  The Royal Bank of Scotland

* `BC`

  Barclays

* `HT`

  Haitong Bank

* `VT`

  Bank Vontobel

* `KC`

  KBC Bank

* `MS`

  Morgan Stanley

* `GJ`

  Guotai Junan

* `XZ`

  DBS Bank

* `HU`

  Huatai

* `KS`

  Korea Investment

* `CI`

  CITIC Securities

## Candlestick Field

> **KL_FIELD**

* `ALL`

  All

* `DATE_TIME`
  
  Time

* `HIGH`

  High

* `OPEN`

  Open

* `LOW`

  Low

* `CLOSE`

  Close

* `LAST_CLOSE`

  Close of the previous K-line

* `TRADE_VOL`

  Volume

* `TRADE_VAL`

  Turnover

* `TURNOVER_RATE`

  Turnover rate

* `PE_RATIO`

  P/E ratio

* `CHANGE_RATE`

  Yield

## Candlestick Type

> **KLType**

* `NONE`

  unknown

* `K_1M`

  1 minute candlestick

* `K_3M`

  3 minutes candlestick  (Option is not supported) 

* `K_5M`

  5 minutes candlestick

* `K_15M`

  15 minutes candlestick

* `K_30M`

  30 minutes candlestick  (Option is not supported) 

* `K_60M`

  60 minutes candlestick

* `K_10M`

  10 minutes candlestick  (Option is not supported)

* `K_120M`

  120 minutes candlestick (2 hours)  (Option is not supported)

* `K_180M`

  180 minutes candlestick (3 hours)  (Option is not supported)

* `K_240M`

  240 minutes candlestick (4 hours)  (Option is not supported)

* `K_DAY`

  1 day candlestick

* `K_WEEK`

  1 week candlestick  (Option is not supported) 

* `K_MON`

  1 month candlestick  (Option is not supported) 

* `K_QUARTER`

  1 quarter candlestick  (Option is not supported) 

* `K_YEAR`

  1 year candlestick  (Option is not supported)

## Period Type

> **PeriodType**

* `INTRADAY`

  Intraday

* `DAY`

  Day

* `WEEK`

  Week

* `MONTH`

  Month

## Price Reminder Market Status

> **PriceReminderMarketStatus**

* `UNKNOW`

  unknown

* `OPEN`

  Market opens

* `US_PRE`

  Pre-market of US stocks

* `US_AFTER`

  After-hours of US stocks

* `US_OVERNIGHT`

  Overnight trading session of US stocks

## Watchlist Operation

> **ModifyUserSecurityOp**

* `NONE`

  Unknown

* `ADD`

  Add

* `DEL`

  Delete

* `MOVE_OUT`

  Remove from group

## Option Type (by Exercise Time)

> **OptionAreaType**

* `NONE`

  unknown

* `AMERICAN`

  American Option

* `EUROPEAN`

  European Option

* `BERMUDA`

  Bermuda Option

## Option in/out of The Money

> **OptionCondType**

* `ALL`

  All

* `WITHIN`

  In the money

* `OUTSIDE`

  Out of the money

## Option Type (by Direction)

> **OptionType**

* `ALL`

  all

* `CALL`

  Call option

* `PUT`

  Put option

## Option Strategy Type

> **OptionStrategyType**

* `NONE`

  Unknown

* `SINGLE`

  Single option

* `COVERED`

  Covered

* `SPREAD`

  Vertical spread

* `STRADDLE`

  Straddle

* `STRANGLE`

  Strangle

* `COLLAR`

  Collar

* `BUTTERFLY`

  Butterfly

* `CONDOR`

  Condor

* `IRON_BUTTERFLY`

  Iron butterfly

* `IRON_CONDOR`

  Iron condor

* `CALENDAR_SPREAD`

  Calendar spread

* `DIAGONAL_SPREAD`

  Diagonal spread

* `CUSTOM`

  Custom

## News Sub Type

> **NewsSubType**

* `ALL`

  All

* `NEWS`

  News

* `NOTICE`

  Notice

* `RATING`

  Rating

## Plate Set Type

> **Plate**

* `ALL`

  All plates

* `INDUSTRY`

  Industry plate

* `REGION`

  Regional plate  (The regional plate of the Hong Kong and US stock markets are temporarily empty.)

* `CONCEPT`

  Concept plate

* `OTHER`

  Other plates  (Only used for the return of the [Get plates of stocks](../quote/get-owner-plate.md) interface and cannot be used as a request parameter of other interfaces.)

## Price Reminder Frequency

> **PriceReminderFreq**

* `NONE`

  Unknown

* `ALWAYS`

  Keep reminding

* `ONCE_A_DAY`

  Once a day

* `ONCE`

  Only remind once

## Price Reminder Type

> **PriceReminderType**

* `NONE`

  Unknown

* `PRICE_UP`

  Price rise to

* `PRICE_DOWN`

  Price fall to

* `CHANGE_RATE_UP`

  Daily increase rate exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `CHANGE_RATE_DOWN`

  Daily decline rate exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `FIVE_MIN_CHANGE_RATE_UP`

  Increate rate in 5 minutes exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `FIVE_MIN_CHANGE_RATE_DOWN`

  Decline rate in 5 minutes exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `VOLUME_UP`

  Volume exceeds

* `TURNOVER_UP`

  Turnover exceeds

* `TURNOVER_RATE_UP`

  Turnover rate exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `BID_PRICE_UP`

  Bid price higher than

* `ASK_PRICE_DOWN`

  Ask price lower than

* `BID_VOL_UP`

  Bid volume higher than

* `ASK_VOL_UP`

  Ask volume higher than

* `THREE_MIN_CHANGE_RATE_UP`

  Increate rate in 3 minutes exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

* `THREE_MIN_CHANGE_RATE_DOWN`

  Decline rate in 3 minutes exceeds  (This field is in percentage form, so 20 is equivalent to 20%.)

## Warrant in/out of the Money

> **PriceType**

* `UNKNOW`

  Unknown

* `OUTSIDE`

  Out of the money

* `WITH_IN`

  In the money

## Quote Push Type

> **PushDataType**

* `UNKNOW`

  Unknown

* `REALTIME`

  Real-time data

* `BYDISCONN`

  Pull supplementary data (up to 50) during disconnection from Futu server

* `CACHE`

  Non-real-time non-supplementary data

## Quote Market

> **Market**

* `NONE`

  Unknown market

* `HK`

  HK market

* `US`

  US market

* `SH`

  Shanghai market

* `SZ`

  Shenzhen market

* `SG`

  Singapore market

* `JP`

  Japanese market

* `AU`

  Australian market

* `MY`

  Malaysian market

* `CA`

  Canadian market  

* `FX`

  Forex market  

* `CC`

  Cryptocurrency market

## Market State

> **MarketState**

Corresponding time period of each market state, [click here](../qa/quote.md#2076) to learn more

* `NONE`

  No trading

* `AUCTION`

  Pre-market trading

* `WAITING_OPEN`

  Waiting for opening

* `MORNING`

  Morning session

* `REST`

  Lunch break

* `AFTERNOON`

  Afternoon session / Regular trading hours for U.S stock market

* `CLOSED`

  Market closed

* `PRE_MARKET_BEGIN`

  Pre-market trading of U.S stock market

* `PRE_MARKET_END`

  Pre-market ending of U.S stock market

* `AFTER_HOURS_BEGIN`

  After-hours trading of U.S stock market

* `AFTER_HOURS_END`

  Market closed of U.S. stock market

* `OVERNIGHT`

  Overnight trading of U.S. stock market

* `NIGHT_OPEN`

  Night market trading hours

* `NIGHT_END`

  Night market closed

* `NIGHT`

  Night market trading hours for U.S. index options

* `TRADE_AT_LAST`

  Late trading hours for U.S. index options

* `FUTURE_DAY_OPEN`

  Day market trading hours

* `FUTURE_DAY_BREAK`

  Day market break

* `FUTURE_DAY_CLOSE`

  Day market closed

* `FUTURE_DAY_WAIT_OPEN`

  Futures market wait for opening

* `HK_CAS`

  After-hours bidding for HK stocks

* `FUTURE_NIGHT_WAIT`

  Futures night market wait for opening (Obsolete)

* `FUTURE_AFTERNOON`

  Futures afternoon (Obsolete)

* `FUTURE_SWITCH_DATE`

  Waiting for U.S. futures opening

* `FUTURE_OPEN`

  Trading hours of U.S. futures

* `FUTURE_BREAK`

  Break of U.S. futures

* `FUTURE_BREAK_OVER`

  Trading hours of U.S. futures after break

* `FUTURE_CLOSE`

  Market closed of U.S. futures

* `STIB_AFTER_HOURS_WAIT`

  After-hours matching period on the Sci-tech innovation plate (Obsolete)

* `STIB_AFTER_HOURS_BEGIN`

  After-hours trading on the Sci-tech innovation plate begins (Obsolete)

* `STIB_AFTER_HOURS_END`

  After-hours trading on the Sci-tech innovation plate ends (Obsolete)

## US Stock Session

> **Session**

* `NONE`

  Unknown

* `RTH`

  US Stocks Regular trading hours

* `ETH`

  US Stocks Pre/Post + regular trading hours

* `OVERNIGHT`

  US Stocks Overnight trading hours (only applied to Trade API)

* `ALL`

  US Stocks 24H trading hours (applied to Quote API & Trade API)


## Quote Authorities

> **QotRight**

* `UNKNOW`

  Unknown

* `BMP`

  BMP (subscription is not supported for this permission)

* `LEVEL1`

  Level1

* `LEVEL2`

  Level2

* `SF`

  HK Securities FullTick Quotes

* `NO`

  No permission

## Associated * **Data Type**

> **SecurityReferenceType**

* `UNKNOW`

  Unknown

* `WARRANT`

  Warrants for stocks

* `FUTURE`

  Contracts related to futures main

## Candlestick Adjustment Type

> **AuType**

* `NONE`

  Actual

* `QFQ`

  Adjust forward

* `HFQ`

  Adjust backward

## Stock Status

> **SecurityStatus**

* `NONE`

  Unknown

* `NORMAL`

  Normal status

* `LISTING`

  To be listed

* `PURCHASING`

  Purchasing

* `SUBSCRIBING`

  Subscribing

* `BEFORE_DRAK_TRADE_OPENING`

  Before the grey market trading opens

* `DRAK_TRADING`

  Ongoing grey market trading

* `DRAK_TRADE_END`

  Grey market trading closed

* `TO_BE_OPEN`

  To be open

* `SUSPENDED`

  Suspended

* `CALLED`

  Called

* `EXPIRED_LAST_TRADING_DATE`

  Expired latest trading date

* `EXPIRED`

  Expired

* `DELISTED`

  Delisted

* `CHANGE_TO_TEMPORARY_CODE`

  During the company action, the trading was closed and transferred to the temporary code trading

* `TEMPORARY_CODE_TRADE_END`

  Temporary trading ends

* `CHANGED_PLATE_TRADE_END`

  Plate changed, the old code is not available for trading

* `CHANGED_CODE_TRADE_END`

  The code has been changed, the old code is not available for trading

* `RECOVERABLE_CIRCUIT_BREAKER`

  Recoverable circuit breaker

* `UN_RECOVERABLE_CIRCUIT_BREAKER`

  Unrecoverable circuit breaker

* `AFTER_COMBINATION`

  After-hours matchmaking

* `AFTER_TRANSATION`

  After-hours trading

## Stock Type

> **SecurityType**

* `NONE`

  Unknown

* `BOND`

  Bonds

* `BWRT`

  Blanket warrants

* `STOCK`

  Stocks

* `ETF`

  ETFs

* `WARRANT`

  Warrants

* `IDX`

  Indexs

* `PLATE`

  Plates

* `DRVT`

  Options

* `PLATESET`

  Plate sets

* `FUTURE`

  Futures

* `CRYPTO`

  Cryptocurrency

## Set Price Reminder Operation Type

> **SetPriceReminderOp**

* `NONE`

  Unknown

* `ADD`

  Add

* `DEL`

  Delete

* `ENABLE`

  Enable

* `DISABLE`

  Disable

* `MODIFY`

  Modify

* `DEL_ALL`

  Delete all (delete all price alerts under the specified stock)

## Sort Direction

> **SortDir**

* `NONE`

  Not sorted

* `ASCEND`

  Ascending

* `DESCEND`

  Descending

## Sort Field

> **SortField**

* `NONE`

  Unknown

* `CODE`

  Code

* `CUR_PRICE`

  Latest price

* `PRICE_CHANGE_VAL`

  Price changed

* `CHANGE_RATE`

  Yield

* `STATUS`

  Status

* `BID_PRICE`

  Bid price

* `ASK_PRICE`

  Ask price

* `BID_VOL`

  Bid volume

* `ASK_VOL`

  Ask volume

* `VOLUME`

  Volume

* `TURNOVER`

  Turnover

* `AMPLITUDE`

  Amplitude

* `SCORE`

  Comprehensive score

* `PREMIUM`

  Premium

* `EFFECTIVE_LEVERAGE`

  Effective leverage

* `DELTA`

  Hedging value  (For puts and calls only)

* `IMPLIED_VOLATILITY`

  Implied volatility  (For puts and calls only)

* `TYPE`

  Type

* `STRIKE_PRICE`

  Strike price

* `BREAK_EVEN_POINT`

  Break even point

* `MATURITY_TIME`

  Maturity date

* `LIST_TIME`

  Listing date

* `LAST_TRADE_TIME`

  Lastest trading day

* `LEVERAGE`

  Leverage ratio

* `IN_OUT_MONEY`

  In/out of the money %

* `RECOVERY_PRICE`

  Recovery price  (For CBBCs only)

* `CHANGE_PRICE`

  Change price

* `CHANGE`

  Change ratio

* `STREET_RATE`

  Outstanding percentage (the propotioin of retail investors)

* `STREET_VOL`

  Outstanding quantity (the volume held by retail investors)

* `WARRANT_NAME`

  Warrant name

* `ISSUER`

  Issuer

* `LOT_SIZE`

  Lot size

* `ISSUE_SIZE`

  Issue size

* `UPPER_STRIKE_PRICE`

  Upper bound  (Only for Inline Warrants)

* `LOWER_STRIKE_PRICE`

  Lower bound  (Only for Inline Warrants)

* `INLINE_PRICE_STATUS`

  In/out of bounds  (Only for Inline Warrants)

* `PRE_CUR_PRICE`

  Latest price of pre-market

* `AFTER_CUR_PRICE`

  Latest price of after-hours

* `PRE_PRICE_CHANGE_VAL`

  Pre-market changes

* `AFTER_PRICE_CHANGE_VAL`

  After-hours changes

* `PRE_CHANGE_RATE`

  Pre-market change rate %

* `AFTER_CHANGE_RATE`

  After-hours change rate %

* `PRE_AMPLITUDE`

  Pre-market amplitude %

* `AFTER_AMPLITUDE`

  After-hours amplitude %

* `PRE_TURNOVER`

  Pre-market turnover

* `AFTER_TURNOVER`

  After-hours turnover

* `LAST_SETTLE_PRICE`

  Last settle price 

* `POSITION`

  Position

* `POSITION_CHANGE`

  Daily increase of position

* `MARKET_CAP`

  Market cap, for use with Qot_GetValuationPlateStockList

* `VALUATION`

  Valuation, for use with Qot_GetValuationPlateStockList

* `FORWARD_VALUATION`

  Forward valuation, for use with Qot_GetValuationPlateStockList

* `HISTORICAL_PERCENTILE`

  Historical percentile, for use with Qot_GetValuationPlateStockList

* `HOLDER_QUANTITY`

  Number of shares held, for use with shareholder protocols

* `SHARE_CHANGE_NUM`

  Change in shares held, for use with shareholder protocols

* `HOLDING_DATE`

  Holding date, for use with shareholder protocols

* `HOLDER_PCT_CHANGE`

  Change ratio in holdings, for use with shareholder protocols

* `HOLDER_CHANGE_AMOUNT`

  Change amount in holdings, for use with shareholder protocols

* `HOLDER_PCT`

  Holding percentage, for use with shareholder protocols

## Sort Order

> **SortType**

* `NONE`

  Unknown

* `DESC`

  Descending

* `ASC`

  Ascending

## Financial Report Type

> **F10Type**

* `NONE`

  Unknown

* `Q1`

  Single quarter report, Q1

* `Q2`

  Single quarter report, Q2

* `Q3`

  Single quarter report, Q3

* `Q4`

  Single quarter report, Q4

* `Q6`

  Cumulative quarter report, Q6 (Q1+Q2)

* `Q9`

  Cumulative quarter report, Q9 (Q1+Q2+Q3)

* `ANNUAL`

  Annual report

* `QUARTERLY`

  Single quarter combination (Q1, Q2, Q3, Q4)

* `QUARTERLY_ANNUAL`

  Single quarter + annual report

* `MUL_QUARTERLY`

  Cumulative quarter reports (Q1, Q6, Q9, Annual)

## Earnings Publication Time Type

> **EarningsPubTimeType**

* `NONE`

  Unknown

* `PRE_MARKET`

  Pre-market

* `AFTER_MARKET`

  After-market

* `DURING_MARKET`

  During market hours

## Valuation Type

> **ValuationType**

* `NONE`

  Unknown

* `PE`

  P/E ratio

* `PB`

  P/B ratio

* `PS`

  P/S ratio

## Financial Statements Type

> **FinancialStatementsType**

* `NONE`

  Unknown

* `INCOME`

  Income statement

* `BALANCE_SHEET`

  Balance sheet

* `CASH_FLOW`

  Cash flow statement

* `MAIN_INDEX`

  Key metrics

## Revenue Breakdown Dimension Type

> **RevenueBreakdownType**

* `NONE`

  Unknown

* `PRODUCT`

  Product

* `INDUSTRY`

  Industry

* `REGION`

  Region

* `BUSINESS`

  Business

## Analyst Rating

> **ResearchRatingType**

* `NONE`

  Unknown

* `SELL`

  Sell

* `UNDERPERFORM`

  Underperform

* `HOLD`

  Hold

* `BUY`

  Buy

* `STRONG_BUY`

  Strong Buy

## Research Rating Dimension Type

> **ResearchRatingDimensionType**

* `NONE`

  Unknown

* `INSTITUTION`

  Institution dimension (default)

* `ANALYST`

  Analyst dimension

## Morningstar Rating Type

> **MorningstarRatingType**

* `NONE`

  Unknown

* `QUANTITATIVE`

  Quantitative rating (system model)

* `QUALITATIVE`

  Qualitative rating (analyst-assigned)

## Valuation Historical Interval Type

> **ValuationIntervalType**

* `NONE`

  Unknown

* `MONTH3`

  3 months

* `MONTH6`

  6 months

* `YEAR1`

  1 year

* `YEAR2`

  2 years

* `YEAR3`

  3 years

* `YEAR5`

  5 years

* `YEAR10`

  10 years

* `YEAR20`

  20 years

* `YEAR30`

  30 years

* `SINCE2019`

  Since 2019

## Corporate Action Reform Type

> **ReformType**

* `NONE`

  Unknown

* `STOCK_SPLIT`

  Stock split

* `STOCK_MERGE`

  Stock merge

* `BONUS_SHARE`

  Bonus share

* `CAPITALIZATION_OF_RESERVES`

  Capitalization of reserves

* `RIGHTS_ISSUE`

  Rights issue

* `NEW_SHARE_ISSUANCE`

  New share issuance

* `CASH_DIVIDEND`

  Cash dividend

* `SPECIAL_DIVIDEND`

  Special dividend

* `SPINOFF`

  Spinoff

## Holding Changes Filter Type

> **HoldingChangesFilterType**

* `NONE`

  All (default)

* `INCREASE`

  Increase

* `DECREASE`

  Decrease

* `NEW_IN`

  New position

* `CLOSE_OUT`

  Close out

## Holder Detail Institution Type

> **HolderDetailType**

* `DEFAULT`

  Default, no filter — server-side default logic applies

* `ALL`

  All

* `UNCLASSIFIED`

  Other institutions

* `TRADITIONAL_INVESTMENT_MANAGER`

  Traditional investment manager

* `HEDGE_FUND_MANAGER`

  Hedge fund

* `VC_OR_PE`

  Venture capital / private equity

* `CORPORATE_PENSION_PLAN_SPONSOR`

  Corporate pension plan

* `FOUNDATION_FUND_SPONSOR`

  Foundation fund

* `INSURANCE_COMPANY`

  Insurance company

* `BANK_OR_INVESTMENT_BANK`

  Bank / investment bank

* `FAMILY_OFFICES_OR_TRUST`

  Family office / trust

* `SOVEREIGN_WEALTH_FUND`

  Sovereign wealth fund

* `REIT`

  REIT

* `STRUCTURED_FINANCE_POOL_MANAGER`

  Structured finance pool manager

* `UNION_PENSION_PLAN_SPONSOR`

  Union pension plan

* `GOVERNMENT_PENSION_PLAN_SPONSOR`

  Government pension plan

* `ENDOWMENT_FUND_SPONSOR`

  Endowment fund

* `INDIVIDUAL_INSIDERS`

  Individual

* `ISSUE_SPONSORED_ADR`

  ADS

* `CORPORATIONS_PUBLIC`

  Public corporation

* `CORPORATIONS_PRIVATE`

  Private corporation

* `STATE_OWNED_SHARES`

  State-owned shares

## Company Profile Field Type

> **CompanyProfileFieldType**

* `SOURCE_TEXT`

  Text

* `LINK_TYPE`

  Link

* `INDEPENDENT_TITLE`

  Independent title

## Broker Net Buy/Sell Direction

> **BuySellType**

* `NONE`

  Unknown

* `NET_BUY`

  Net buy

* `NET_SELL`

  Net sell

## Option Volatility Query Time Period Type

> **OptionVolatilityTimePeriodType**

* `NONE`

  Unknown

* `WEEK`

  Week

* `MONTH`

  Month (default)

* `QUARTER`

  Quarter

* `HALF_YEAR`

  Half year

* `YEAR`

  Year

## Option Implied Volatility Status Type

> **OptionImpvolStatusType**

* `IMPVOL_FLUCTUATING`

  Option implied volatility is fluctuating

* `IMPVOL_OVERVALUED`

  Option implied volatility is overvalued

* `IMPVOL_UNDERVALUED`

  Option implied volatility is undervalued

## Simple Filter Properties

> **StockField**

* `NONE`

  unknown

* `STOCK_CODE`

  Stock code, does not accept list inputs as an interval

* `STOCK_NAME`

  Stock name, does not accept list inputs as an interval

* `CUR_PRICE`

  The latest price  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [10, 20])

* `CUR_PRICE_TO_HIGHEST52_WEEKS_RATIO`

  **(CP - WH52) / WH52** <br>
  **CP**: Current price <br>
  **WH52**: 52-week high <br>
  Corresponding to the “percentage from 52-week high” on the PC terminal  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-30, -10]) 

* `CUR_PRICE_TO_LOWEST52_WEEKS_RATIO`

  **(CP - WL52) / WL52** <br>
  **CP**: Current price <br>
  **WL52**: 52-week low <br>
  Corresponding to the “percentage from 52-week low” on the PC terminal  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [20, 40]) 

* `HIGH_PRICE_TO_HIGHEST52_WEEKS_RATIO`

  **(TH - WH52) / WH52**<br>
  **TH**: Today's high<br>
  **WH52**: 52-week high<br>
    (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-3, -1]) 

* `LOW_PRICE_TO_LOWEST52_WEEKS_RATIO`

  **(TL - WL52) / WL52**<br>
  **TL**: Today's low<br>
  **WL52**: 52-week low<br>
    (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [10, 70]) 

* `VOLUME_RATIO`

  Volume ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [0.5, 30])

* `BID_ASK_RATIO`

  Bid-ask ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-20, 80.5]) 

* `LOT_PRICE`

  Price per lot  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [40, 100])

* `MARKET_VAL`

  Market value  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [50000000, 3000000000])

* `PE_ANNUAL`

  Trailing P/E  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [-8, 65.3])

* `PE_TTM`

  P/E TTM  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [-10, 20.5])

* `PB_RATE`

  P/B ratio  (- 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [0.5, 20]) 

* `CHANGE_RATE_5MIN`

  Change rate in 5 minutes  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-5, 6.3]) 

* `CHANGE_RATE_BEGIN_YEAR`

  Price change rate from this year  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [-50.1, 400.7]) 

* `PS_TTM`

  P/S TTM  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [100, 500])

* `PCF_TTM`

  PCF TTM  (- 3 decimal place accuracy, the excess part is discarded.
  - This field is in percentage form, so 20 is equivalent to 20%.
  - For example, a range of [100, 1000])

* `TOTAL_SHARE`

  Total number of shares  (- unit: share.
  - 0 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `FLOAT_SHARE`

  Shares outstanding  (- unit: share.
  - 0 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

* `FLOAT_MARKET_VAL`

  Market value outstanding  (- unit: yuan.
  - 3 decimal place accuracy, the excess part is discarded.
  - For example, a range of [1000000000, 1000000000])

## Subscription Type

> **SubType**

* `NONE`

  Unknown

* `QUOTE`

  Basic quote

* `ORDER_BOOK`

  Order book

* `TICKER`

  Tick-by-tick

* `RT_DATA`

  Time Frame

* `K_DAY`

  Daily candlesticks

* `K_5M`

  5 minutes candlesticks

* `K_15M`

  15 minutes candlesticks

* `K_30M`

  30 minutes candlesticks

* `K_60M`

   60 minutes candlesticks

* `K_1M`

  1 minute candlesticks

* `K_WEEK`

  Weekly candlesticks

* `K_MON`

  Monthly candlesticks

* `BROKER`

  Broker's queue

* `K_QURATER`

  Seasonal candlesticks

* `K_YEAR`

  Annual candlesticks

* `K_3M`

  3 minutes candlesticks

* `K_10M`

  10 minutes candlesticks

* `K_120M`

  120 minutes candlesticks (2 hours)

* `K_180M`

  180 minutes candlesticks (3 hours)

* `K_240M`

  240 minutes candlesticks (4 hours)

* `ORDER_BOOK_ODD`

  Odd lot order book

## Order Book Type

> **OrderBookType**

* `NORMAL`

  Normal order book (default)

* `ODD`

  Odd lot order book

## Transaction Direction

> **TickerDirect**

* `NONE`

  unknown

* `BUY` 

  Active buy  (Active buy, a buyer actively buys stocks at the then sell price or higher price.) 

* `SELL`

  Active sell  (Active sell, a seller actively sells stocks at the then buy price or lower price.) 

* `NEUTRAL`

  Neutral transaction  (Neutral transaction, the stock price is between the bid price and ask price.)

## Tick-by-Tick Transaction Type

> **TickerType**

* `UNKNOWN`

  Unknown

* `AUTO_MATCH`

  Regular sale

* `LATE`

  Pre-market trade

* `NON_AUTO_MATCH`

  Non-regular sale

* `INTER_AUTO_MATCH`

  Regular sale for same broker

* `INTER_NON_AUTO_MATCH`

  Non-regular sale for same broker

* `ODD_LOT`

  Odd lot trade

* `AUCTION`

  Auction trade

* `BULK`

  Bunched trade

* `CRASH`

  Cash trade

* `CROSS_MARKET`

  Intermarket sweep

* `BULK_SOLD`

  Bunched sold trade

* `FREE_ON_BOARD`

  Price variation trade

* `RULE127_OR155`

  Rule 127 (NYSE only) or Rule 155 (NYSE MKT only)

* `DELAY`

  Delay the transaction

* `MARKET_CENTER_CLOSE_PRICE`

  Market center close price

* `NEXT_DAY`

  Next day

* `MARKET_CENTER_OPENING`

  Market center opening trade

* `PRIOR_REFERENCE_PRICE`

  Prior reference price

* `MARKET_CENTER_OPEN_PRICE`

  Market center open price

* `SELLER`

  Seller

* `T`

  Form T(pre-open and post-close market trade)

* `EXTENDED_TRADING_HOURS`

  Extended trading hours/sold out of sequence

* `CONTINGENT`

  Contingent trade

* `AVERAGE_PRICE`

  Average price trade

* `OTC_SOLD`

  Sold(out of sequence)

* `ODD_LOT_CROSS_MARKET`

  Odd lot cross trade

* `DERIVATIVELY_PRICED`

  Derivatively priced

* `REOPENINGP_RICED`

  Re-Opening price

* `CLOSING_PRICED`

  Closing price

* `COMPREHENSIVE_DELAY_PRICE`

  Consolidated late price per listing packet

* `OVERSEAS`

  One party to the transaction is not a member of the Hong Kong Stock Exchange and is an over-the-counter transaction

## Check The Market on The Trading Day

> **TradeDateMarket**

* `NONE`

  Unknown

* `HK`

  HK market   (- Including stocks, ETFs, warrants, CBBCs, options, non-holiday trading futures
  - Excluding holiday trading futures)

* `US`

  US market  (- Including stocks, ETFs, options
  - Excluding futures)

* `CN`

  A-share market

* `NT`

  Northbound Trading

* `ST`

  Southbound Trading

* `JP_FUTURE`

  Japanese future market

* `SG_FUTURE`

  Singapore future market

## Type of Trading Day

> **TradeDateType**

* `WHOLE`

  Whole day trading

* `MORNING`

  Trading in the morning, closed in the afternoon

* `AFTERNOON`

  Trading in the afternoon, closed in the morning

## Warrant Status

> **WarrantStatus**

* `NONE`

  Unknown

* `NORMAL`

  Normal status

* `SUSPEND`

  Suspended

* `STOP_TRADE`

  Stop trading

* `PENDING_LISTING`

  Waiting to be listed

## Warrant Type

> **WrtType**

* `NONE`

  Unknown

* `CALL`

  Long warrants

* `PUT`

  Short warrants

* `BULL`

  Call warrants

* `BEAR`

  Put warrants

* `INLINE`

  Inline Warrants

## Exchange Type

> **ExchType**

* `NONE`

  Unknown

* `HK_MAINBOARD`

  HKEx·Main Board 

* `HK_GEMBOARD`

  HKEx·GEM

* `HK_HKEX`

  HKEx

* `US_NYSE`

  NYSE

* `US_NASDAQ`

  NASDAQ

* `US_PINK`

  OTC Mkt

* `US_AMEX`

  AMEX

* `US_OPTION`

  US  (Only applicable to US Options.) 

* `US_NYMEX`

  NYMEX

* `US_COMEX `

  COMEX

* `US_CBOT`

  CBOT 

* `US_CME`

  CME

* `US_CBOE`

  CBOE 

* `CN_SH`

  SH Stock Ex

* `CN_SZ`

  SZ Stock Ex   

* `CN_STIB`

  STAR

* `SG_SGX`

  SGX

* `JP_OSE`

  OSE

* `CC_CRYPTO`

  Cryptocurrency Exchange

## Quote Common Parameter Header

**QotHeader**

```protobuf
message QotHeader
{
    optional int32 securityFirm = 1; //Security firm identifier, see Trd_Common.SecurityFirm
}
```

## Security Identification

**Security**

```protobuf
message Security
{
    required int32 market = 1; //QotMarket, quote market
    required string code = 2; //Code
}
```

## Candlestick data

**KLine**

```protobuf
message KLine
{
    required string time = 1; //String of timestamp (Format: yyyy-MM-dd HH:mm:ss)
    required bool isBlank = 2; //Whether it is a point with empty content, if it is true, only time information
    optional double highPrice = 3; //High
    optional double openPrice = 4; //Open
    optional double lowPrice = 5; //Low
    optional double closePrice = 6; //Close
    optional double lastClosePrice = 7; //Close of the previous K-line
    optional int64 volume = 8; //Volume
    optional double turnover = 9; //Turnover
    optional double turnoverRate = 10; // Turnover rate (this field is in decimal form, so 0.2 is equivalent to 20%)
    optional double pe = 11; //P/E ratio
    optional double changeRate = 12; //Yield (This field is in percentage form, so 20 is equivalent to 20%.)
    optional double timestamp = 13; //Timestamp
}
```

## Option Specific Fields of The Underlying Quote

**OptionBasicQotExData**

```protobuf
message OptionBasicQotExData
{
    required double strikePrice = 1; //Strike price
    required int32 contractSize = 2; //Contract size (integer)
    optional double contractSizeFloat = 17; //Contract size (float)
    required int32 openInterest = 3; //Number of open positions
    required double impliedVolatility = 4; //Implied volatility (This field is in percentage form, so 20 is equivalent to 20%.)
    required double premium = 5; //Premium (This field is in percentage form, so 20 is equivalent to 20%.)
    required double delta = 6; //Greek value Delta
    required double gamma = 7; //Greek value Gamma
    required double vega = 8; //Greek value Vega
    required double theta = 9; //Greek value Theta
    required double rho = 10; //Greek value Rho
    optional int32 netOpenInterest = 11; //Net open contract number , only HK options support this field
    optional int32 expiryDateDistance = 12; //The number of days from the expiry date, a negative number means it has expired.
    optional double contractNominalValue = 13; //Contract nominal amount , only HK options support this field
    optional double ownerLotMultiplier = 14; //Equal number of underlying stocks, index options do not have this field , only HK options support this field  
    optional int32 optionAreaType = 15; //OptionAreaType, option type (by exercise time).
    optional double contractMultiplier = 16; //Contract multiplier
    optional int32 indexOptionType = 18; //Qot_Common.IndexOptionType, index option type
}    
```

## Futures Specific Fields of The Base Quote

**FutureBasicQotExData**

```protobuf
message FutureBasicQotExData
{
    required double lastSettlePrice = 1; //Close yesterday
    required int32 position = 2; //Hold position
    required int32 positionChange = 3; //Daily change in position
    optional int32 expiryDateDistance = 4; //The number of days from the expiration date
}    
```

## Basic Quotation

**BasicQot**

```protobuf
message BasicQot
{
    required Security security = 1; //Stock
    optional string name = 24; // stock name
    required bool isSuspended = 2; //whether trading is suspended
    required string listTime = 3; //listed date string (This field is deprecated. Format: yyyy-MM-dd)
    required double priceSpread = 4; //Spread
    required string updateTime = 5; //Update time string of the latest price (Format: yyyy-MM-dd HH:mm:ss), not applicable to other fields
    required double highPrice = 6; //High
    required double openPrice = 7; //Open
    required double lowPrice = 8; //low
    required double curPrice = 9; //The latest price
    required double lastClosePrice = 10; //Close yesterday
    required int64 volume = 11; //Volume
    required double turnover = 12; //Turnover
    required double turnoverRate = 13; //Turnover rate (This field is in percentage form, so 20 is equivalent to 20%.)
    required double amplitude = 14; //Amplitude (This field is in percentage form, so 20 is equivalent to 20%.)
    optional int32 darkStatus = 15; //Grey market trading status
    optional OptionBasicQotExData optionExData = 16; //Option specific field
    optional double listTimestamp = 17; //Time stamp of listing date (This field is deprecated.)
    optional double updateTimestamp = 18; //Update timestamp of the latest price, not applicable to other fields
    optional PreAfterMarketData preMarket = 19; //Pre-market data
    optional PreAfterMarketData afterMarket = 20; //After-hours data
    optional int32 secStatus = 21; //Security status
    optional FutureBasicQotExData futureExData = 22; //Futures specific field
}
```

## Before And After Data

**PreAfterMarketData**
 
```protobuf
//US stocks support pre-market and after-hours data
//The Sci-tech Innovation Plate only supports after-hours data: trading volume, turnover
message PreAfterMarketData
{
    optional double price = 1; //Pre-market or after-hours## Price
    optional double highPrice = 2; //Pre-market or after-hours## High
    optional double lowPrice = 3; //Pre-market or after-hours## Low
    optional int64 volume = 4; //Pre-market or after-hours## Volume
    optional double turnover = 5; //Pre-market or after-hours## Turnover
    optional double changeVal = 6; //Pre-market or after-hours## Change in price
    optional double changeRate = 7; //Pre-market or after-hours## Yield (This field is in percentage form, so 20 is equivalent to 20%.)
    optional double amplitude = 8; //Pre-market or after-hours## Amplitude (This field is in percentage form, so 20 is equivalent to 20%.)
}
```

## Time Frame Data

**TimeShare**

```protobuf
message TimeShare
{
    required string time = 1; //Time string (Format: yyyy-MM-dd HH:mm:ss)
    required int32 minute = 2; //Minutes after 0 o'clock
    required bool isBlank = 3; //Whether the content is empty, if true, it contents only time
    optional double price = 4; //Current price
    optional double lastClosePrice = 5; //Close yesterday
    optional double avgPrice = 6; //Average price
    optional int64 volume = 7; //Volume
    optional double turnover = 8; //Turnover
    optional double timestamp = 9; //Timestamp
}
```

## Basic Static Information of Securities

**SecurityStaticBasic**

```protobuf

message SecurityStaticBasic
{
    required Qot_Common.Security security = 1; //Stock
    required int64 id = 2; //Stock ID
    required int32 lotSize = 3; //Lot size, the option type represents the number of shares in a contract
    required int32 secType = 4; //Qot_Common.SecurityType, stock type
    required string name = 5; //Stock name
    required string listTime = 6; //Listing time string (This field is deprecated. Format: yyyy-MM-dd)
    optional bool delisting = 7; //Delisted or not
    optional double listTimestamp = 8; //Listing timestamp (This field is deprecated.)
    optional int32 exchType = 9; //Qot_Common.ExchType, Exchange Type
}
```

## Warrant Additional Static Information
**WarrantStaticExData**

```protobuf
message WarrantStaticExData
{
    required int32 type = 1; //Qot_Common.WarrantType, Warrant Type
    required Qot_Common.Security owner = 2; //The underlying stock
}   
```
## Option Additional Static Information

**OptionStaticExData**

```protobuf
message OptionStaticExData
{
    required int32 type = 1; //Qot_Common.OptionType, option
    required Qot_Common.Security owner = 2; //Underlying stock
    required string strikeTime = 3; //Exercise date (Format: yyyy-MM-dd)
    required double strikePrice = 4; //Strike price
    required bool suspend = 5; //Suspended or not
    required string market = 6; //Issuance market name
    optional double strikeTimestamp = 7; //Exercise date timestamp
    optional int32 indexOptionType = 8; //Qot_Common.IndexOptionType, type of index option, only valid for index option
    optional int32 expirationCycle = 9; // Qot_Common.ExpirationCycle, type of option expiration cycle
    optional int32 optionStandardType = 10; // Qot_Common.OptionStandardType, type of option standard
    optional int32 optionSettlementMode = 11; // OptionSettlementMode, mode of option settlement
}   
```

## Additional Static Information About Futures

**FutureStaticExData**

```protobuf
message FutureStaticExData
{
    required string lastTradeTime = 1; //The lastest trading day, only future non-main contracts have this field
    optional double lastTradeTimestamp = 2; //The lastest trading day timestamp, only future non-main contracts have this field
    required bool isMainContract = 3; //Futures main contract or not
}    
```

## Securities Static Information

**SecurityStaticInfo**

```protobuf
message SecurityStaticInfo
{
    required SecurityStaticBasic basic = 1; //Basic security information
    optional WarrantStaticExData warrantExData = 2; //Additional information for warrants
    optional OptionStaticExData optionExData = 3; //Additional information for options
    optional FutureStaticExData futureExData = 4; //Additional information for futures
}
```

## Brokerage

**Broker**

```protobuf
message Broker
{
    required int64 id = 1; //Broker ID
    required string name = 2; //Broker name
    required int32 pos = 3; //Broker position
  
    //The following fields are specific to SF quote
    optional int64 orderID = 4; //Exchange order ID, which is different from the order ID returned by the trading interface
    optional int64 volume = 5; //Number of shares in order
}
```

## Tick-by-Tick

**Ticker**

```protobuf
message Ticker
{
    required string time = 1; //Time string (Format: yyyy-MM-dd HH:mm:ss)
    required int64 sequence = 2; //Unique identification
    required int32 dir = 3; //TickerDirection, buy or sell direction
    required double price = 4; //Price
    required int64 volume = 5; //Volume
    required double turnover = 6; // turnover
    optional double recvTime = 7; //Local timestamp of received push data, used to locate delay
    optional int32 type = 8; //TickerType, type by pen
    optional int32 typeSign = 9; //Pattern-by-stroke type sign
    optional int32 pushDataType = 10; //Used to distinguish push situations, this field is only available when pushing
    optional double timestamp = 11; //time stamp}
}
```
## Transaction File Details

**OrderBookDetail**

```protobuf
message OrderBookDetail
{
    required int64 orderID = 1; //Exchange order ID, which is different from the order ID returned by the trading interface
    required int64 volume = 2; //Number of shares in order
}
```

## Order Book

**OrderBook**

```protobuf
message OrderBook
{
    required double price = 1; //Order price
    required int64 volume = 2; //Order quantity
    required int32 orederCount = 3; //Number of commissioned orders
    repeated OrderBookDetail detailList = 4; //Order information, unique to HK SF, US LV2 market
}
```

## Changes in Holdings

**ShareHoldingChange**

```protobuf
message ShareHoldingChange
{
    required string holderName = 1; //Holder name (institution name or fund name or executive name)
    required double holdingQty = 2; //Current number of holdings
    required double holdingRatio = 3; //Current shareholding percentage (This field is in percentage form, so 20 is equivalent to 20%.)
    required double changeQty = 4; //The number of changes from the previous time
    required double changeRatio = 5; //The percentage of change from the last time (This field is in percentage form, so 20 is equivalent to 20%.. It is the ratio relative to itself, not to total. For example, if the total share capital is 10,000 shares, holding 100 shares, the shareholding percentage is 1%, if 50 shares are sold, the change ratio is 50% instead of 0.5%)
    required string time = 6; //Release time (Format: yyyy-MM-dd HH:mm:ss)
    optional double timestamp = 7; //Timestamp
}
```

## Single Subscription Type Information

**SubInfo**

```protobuf
message SubInfo
{
    required int32 subType = 1; //Qot_Common.SubType, subscription type
    repeated Qot_Common.Security securityList = 2; //Subscribe to securities of this type of market
}
```

## Single Connection Subscription Information

**ConnSubInfo**

```protobuf
message ConnSubInfo
{
    repeated SubInfo subInfoList = 1; //The connection subscription information
    required int32 usedQuota = 2; //The subscription quota that the connection has used
    required bool isOwnConnData = 3; //Used to distinguish whether it is self-connected data
    optional int32 securityFirm = 4; //Security firm identifier, see Trd_Common.SecurityFirm
}
```

## Plate Information

**PlateInfo**

```protobuf
message PlateInfo
{
    required Qot_Common.Security plate = 1; //Plate
    required string name = 2; //Plate name
    optional int32 plateType = 3; //Plate type, only 3207 (to get the plate to which the stock belongs) agreement returns this field
}
```

## Adjustment Information

**Rehab**

```protobuf
message Rehab
{
    required string time = 1; //Time string (Format: yyyy-MM-dd)
    required int64 companyActFlag = 2; //CompanyAct combination flag bit, which specifies whether certain field values ​​are valid
    required double fwdFactorA = 3; //Adjustments factor A
    required double fwdFactorB = 4; //Adjustments factor B
    required double bwdFactorA = 5; //Adjustments factor A
    required double bwdFactorB = 6; //Adjustments factor B
    optional int32 splitBase = 7; //Stock split (for example, 1 split 5, Base is 1, Ert is 5)
    optional int32 splitErt = 8;
    optional int32 joinBase = 9; //Reverse stock split (for example, 50 in 1, Base is 50, Ert is 1)
    optional int32 joinErt = 10;
    optional int32 bonusBase = 11; //Bonus shares (for example, 10 free 3, Base is 10, Ert is 3)
    optional int32 bonusErt = 12;
    optional int32 transferBase = 13; //Transfer bonus shares (for example, 10 to 3, Base is 10, Ert is 3)
    optional int32 transferErt = 14;
    optional int32 allotBase = 15; //Allotment (for example, 10 get 2 free, allotment price is 6.3 yuan, Base is 10, Ert is 2, and Price is 6.3)
    optional int32 allotErt = 16;
    optional double allotPrice = 17;
    optional int32 addBase = 18; //Additional shares (for example, 10 get 2 free, additional issuance price is 6.3 yuan, Base is 10, Ert is 2, and Price is 6.3)
    optional int32 addErt = 19;
    optional double addPrice = 20;
    optional double dividend = 21; //Cash dividend (for example, if every 10 shares are paid out 0.5 yuan, the field value is 0.05)
    optional double spDividend = 22; //Special dividend (for example, if a special dividend is 0.5 yuan for every 10 shares, the value of this field is 0.05)
    optional double timestamp = 23; //Timestamp
}
```

> - For CompanyAct combination flag bit, refer to [CompanyAct](./quote.html#4631).

## Combo Leg Information

**ComboLeg**

```protobuf
message ComboLeg
{
    required Qot_Common.Security security = 1; //Stock / option
    optional int32 side = 2; //Direction, refer to Trd_Common.TrdSide
    optional double qtyRatio = 3; //Quantity ratio
    optional uint64 positionID = 4; //Position ID. Fill in only when closing moomoo JP positions; must be the positionID from option strategy view positions when showOptionStrategyView=True.
}
```

## Expiration Cycle
>**ExpirationCycle**

* `NONE`

  Unknown

* `WEEK`

  Weekly options

* `MONTH`

  Monthly options
  
* `END_OF_MONTH`

  End-Of-Monthly options
  
* `QUARTERLY`

  Quarterly options
  
* `WEEKMON`

  Monthly options-Monday
  
* `WEEKTUE`

  Monthly options-Tuesday
  
* `WEEKWED`

  Monthly options-Wednesday
  
* `WEEKTHU`

  Monthly options-Thursday
  
* `WEEKFRI`

  Monthly options-Friday

## Option Standard Type
>**OptionStandardType**

* `NONE`

  Unknown

* `STANDARD`

  standard options

* `NON_STANDARD`

  non-standard options

## Option Settlement Mode
>**OptionSettlementMode**

* `NONE`

  Unknown

* `AM`

  Asian Pricing

* `PM`

  Path-Dependent
## Stockholder (Deprecated)

## Stock Holder
> **StockHolder**

* `NONE`

  Unknown

* `INSTITUTE`

  Institute

* `FUND`

  Fund

* `EXECUTIVE`

  Executives

## Screening V2 - SimpleField

> Used for the `add_simple_field(field, values)` method of [get_stock_screen](./get-stock-screen.md). All numeric fields accept raw values; OpenD performs magnification conversion automatically.

field|Meaning|values
:-|:-|:-
1|MARKET|ScrMarket: HK=1, US=2, CN=3, SG=4, CA=5, AU=6, JA=7, MY=8
2|EXCHANGE / Listing venue|See [QotMarket](#427)
3|INDEX_ID|Index constituent ID
4|USE_WATCHLIST|0=No, 1=Yes
5|HAS_ADR Whether the stock has a related ADR|0/1
6|HAS_OPTION Whether the stock has options|0/1
7|HAS_WARRANT Whether the stock has warrants|0/1
8|HAS_FUTURE Whether the stock has futures|0/1
9|HAS_AH_STOCK Whether the stock has an A/H counterpart|0/1
10|IS_ISLAMIC Islamic stock|0/1
11|NORTH_BOUND_ID Northbound plate|Shanghai/Shenzhen Connect ID
12|MM_EXCLUSIVE_ID Moomoo exclusive plate|Plate ID

> For the full enum, see the `SimpleField` / `ScrMarket` classes in `stock_screen_const.py` of the SDK.

## Screening V2 - SimpleProperty

> Used by `add_simple_property(name, lower, upper)` and `add_retrieve_simple(name)`. Common factors are listed below; all numeric values are raw.

name|Meaning
:-|:-
2101|LONG_MARGIN_ALLOWED Whether margin (long) is allowed (0/1)
2103|SHORT_MARGIN_ALLOWED Whether short selling is allowed (0/1)
2201|PRICE Last price
2202|OPEN_PRICE Open price
2203|LAST_CLOSE Previous close
2204|HIGH Today's high
2205|LOW Today's low
2217|VOLUME_RATIO Volume ratio
2218|BID_ASK_RATIO Bid-ask ratio
2301|MARKET_CAP Market cap
2302|PE_ANNUAL Static PE
2303|PE_TTM PE TTM
2304|PB Price/Book
2305|DIVIDEND_RATIO Dividend yield
2306|LISTED_DATE Listing date (timestamp)
2307|LISTED_DAYS Days since listing

> See the `SimpleProperty` class for the full enum (including margin trading, pre/post-market, overnight session, high-precision quotes, etc., 60+ items in total).

## Screening V2 - CumulativeProperty

> Used by `add_cumulative_property(name, days, lower, upper)` and `add_retrieve_cumulative(name, days)`. Requires the `days` argument.

name|Meaning
:-|:-
3101|PRICE_CHANGE Price change
3102|PRICE_CHANGE_PCT Price change ratio (%)
3103|AMPLITUDE Price amplitude (%)
3104|AVG_VOLUME Average volume
3105|AVG_TURNOVER Average turnover
3106|TURNOVER_RATIO Turnover ratio (%)
3107|HIGH_TO_N_DAY_HIGH (today's high - N-day high) / N-day high
3108|LOW_TO_N_DAY_LOW (today's low - N-day low) / N-day low
3109|PRICE_CHANGE_HP High-precision price change

## Screening V2 - FinancialProperty

> Used by `add_financial_property(name, term, year, lower, upper)` and `add_retrieve_financial(name, term, year)`. Requires the `term` argument.

* **Common factors (see the `FinancialProperty` class for the full enum, covering profitability / solvency / operating / growth / cash flow / financial surprise, 100+ items in total)**

    name|Meaning
    :-|:-
    4101|NET_PROFIT Net profit
    4102|NET_PROFIT_GROWTH Net profit growth rate
    4105|REVENUE Revenue
    4106|REVENUE_GROWTH Revenue growth rate
    4107|NET_PROFIT_RATIO Net profit margin
    4108|GROSS_PROFIT_RATIO Gross profit margin
    4109|DEBT_TO_ASSETS Debt-to-assets ratio
    4110|ROE Return on equity
    4202|ROIC Return on invested capital
    4801|BASIC_EPS Basic EPS
    4901|TOTAL_SHARE Total shares
    4903|FLOAT_MARKET_CAP Float market cap
    4904|PS_TTM Price-to-sales (TTM)
    4905|PCF_TTM Price-to-cash-flow (TTM)

* **Term** (`Term` enum)

    term|Meaning
    :-|:-
    1 / 2 / 3 / 4|Q1 / Q2 / Q3 / Q4 single quarter
    6|Q6 interim report (cumulative)
    9|Q9 third-quarter report (cumulative)
    10|LATEST Latest single quarter
    100|ANNUAL Annual report (FY)
    200~204|SURPRISE_LATEST series (financial forecast)

## Screening V2 - Indicator / Pattern / Period / Position

> Used by `add_indicator_positional` / `add_indicator_pattern` / `add_retrieve_indicator`.

* **`Indicator` technical indicators** (`first_indicator_name` / `second_indicator` of `add_indicator_positional`)

    name|Meaning
    :-|:-
    1|PRICE Last price
    11~17|MA5 / MA10 / MA20 / MA30 / MA60 / MA120 / MA250
    18|MA Dynamic simple moving average (requires indicator_params)
    21~27|EMA5 / EMA10 / EMA20 / EMA30 / EMA60 / EMA120 / EMA250
    28|EMA Dynamic exponential moving average
    31~33|KDJ_K / KDJ_D / KDJ_J (KDJ(9,3,3))
    41~43|MACD_DIF / MACD_DEA / MACD_MACD (MACD(12,26,9))
    51|RSI_12
    52|RSI Dynamic
    61~63|BOLL_UPPER / BOLL_MIDDLE / BOLL_LOWER (BOLL(20,2))
    71|RVOL Dynamic relative volume

* **`Pattern`** (`name` of `add_indicator_pattern`)

    name|Meaning
    :-|:-
    1 / 2|MA bullish / bearish alignment
    3 / 4|EMA bullish / bearish alignment
    11 / 12|KDJ low-level golden cross / high-level death cross
    13 / 14|KDJ top divergence / bottom divergence
    21 / 22|MACD low-level golden cross / high-level death cross
    23 / 24|MACD top divergence / bottom divergence
    31 / 32|RSI low-level golden cross / high-level death cross
    33 / 34|RSI top divergence / bottom divergence

* **`Period`**

    period|Meaning
    :-|:-
    1 / 2 / 3 / 4|1 / 3 / 5 / 15 minutes
    5|HOUR_1 1 hour
    6|MINUTE_30 30 minutes
    11 / 21 / 31|DAY / WEEK / MONTH

* **`Position`**

    position|Meaning
    :-|:-
    1|OVER first is above second
    2|BELOW first is below second
    3|CROSS_UP first crosses above second
    4|CROSS_DOWN first crosses below second

* **`ScrSortDir` sort direction** (`direction` of `set_sort` / `add_sort`)

    direction|Meaning
    :-|:-
    1|ASC ascending
    2|DESC descending
    3|ABS_ASC absolute-value ascending
    4|ABS_DESC absolute-value descending

## Screening V2 - BasicProperty / Retrieve fields

> Used by retrieve methods such as `add_retrieve_basic(name)`. Other retrieve methods like `add_retrieve_simple` / `add_retrieve_cumulative` / `add_retrieve_financial` share the SimpleProperty / CumulativeProperty / FinancialProperty IDs above.

* **`BasicProperty` basic properties**

    name|Meaning|Notes
    :-|:-|:-
    1101|CODE Stock code|sval
    1102|NAME Stock name|sval
    1103|INDUSTRY Industry|sval

> Each result fills `sval(1)` / `ival(2)` / `aval(3)` / `dval(4)` according to its `value_type`. When ival is an enum code, `enum_name` is decoded by the SDK (e.g. K-line shape returns `'DOUBLE_BOTTOMS'`).

## Option Screening - OptUnderlyingIndicator

> Used by `add_underlying_filter(indicator_type, ...)` and `add_underlying_retrieve(indicator_type)` of [get_option_screen](./get-option-screen.md).

indicator_type|Meaning|Notes
:-|:-|:-
101|STOCK_LIST Specified underlying range|Pass a list of security code strings directly in values, e.g. ["US.AAPL", "HK.00700"]
103|PLATE Specified plate|**Not yet supported on the backend; passing it raises an error**
106|INDEX_LIST Specified index type|
201|VOLUME Total volume|
202|OPEN_INTEREST Total open interest|
203|IV Underlying implied volatility|
204|HV Underlying historical volatility|
205|IV_RANK|
206|IV_PERCENTILE|
207 / 208|IV_CHANGE / IV_CHANGE_RATIO|
209 / 210|IV_HV_RATIO / IV_HV_SPREAD|
401|MARKET_CAP Underlying market cap|
402|STOCK_PRICE Underlying last price|
403|CHANGE_RATIO Change ratio|

## Option Screening - OptIndicator

> Used by `add_option_filter(indicator_type, ...)` and `add_option_retrieve(indicator_type)`.

indicator_type|Meaning|Notes
:-|:-|:-
1001|STRIKE_PRICE Strike price|
1002|LEFT_DAY Days to expiration|
1003|OPTION_TYPE Option type|1=CALL, 2=PUT
1004|EXERCISE_TYPE Exercise type|1=American, 2=European
1005|EXPIRATION_TYPE Expiration type|1=Weekly, 2=Monthly, 3=Quarterly
1007|STRIKE_DATE_TIMESTAMP Maturity date timestamp (seconds)|
2001|IN_THE_MONEY|0=OTM, 1=ITM
2002~2005|PRICE / MID_PRICE / BID_PRICE / ASK_PRICE|
2006~2009|BID_ASK_SPREAD / BID_VOLUME / ASK_VOLUME / BID_ASK_VOLUME_RATIO|
2010|CHANGE_RATIO Change ratio|
2011 / 2012|VOLUME / TURNOVER|
2013 / 2014|OPEN_INTEREST / OPEN_INTEREST_MARKET_CAP|
2018|VOL_OI_RATIO|
2021|PREMIUM|**Only sort/retrieve, filter is not supported**
3001 / 3002 / 3003|IMPLIED_VOLATILITY / HISTORY_VOLATILITY / IV_HV_RATIO|
3004~3008|DELTA / GAMMA / VEGA / THETA / RHO|
3009 / 3010|LEVERAGE_RATIO / EFFECTIVE_GEARING|
3011 / 3012|BUY_TO_BEP / SELL_TO_BEP|
3013 / 3014|BUY_PROFIT_PROBABILITY / SELL_PROFIT_PROBABILITY|
3015~3018|INTRINSIC_VALUE_PER / TIME_VALUE_PER / ITM_DEGREE / OTM_DEGREE|
3019 / 3020|ITM_PROBABILITY / OTM_PROBABILITY|

## Warrant Screening V2 - WarrantField

> Used by `add_interval_filter(field_id, ...)` / `add_choice_filter(field_id, choices)` / `add_sort(field_id, desc)` of [get_warrant_screen](./get-warrant-screen.md). All numeric fields accept raw values.

field_id|Meaning|Filter type
:-|:-|:-
1|CODE Security code|choice (text)
2|NAME Stock name|choice (text)
4|ISSUER_ID Issuer ID|choice
5|STOCK_OWNER Underlying stock ID|choice (accepts "HK.00700")
6|WARRANT_TYPE Warrant type|choice: 1=Call, 2=Put, 3=Bull, 4=Bear, 5=Inline
7|CONVERSION_RATIO Conversion ratio|interval
8|CURRENT_PRICE Current price|interval
9|STREET_RATIO Street ratio|interval
10|VOLUME|interval
11|MATURITY_DATE Maturity date (timestamp seconds)|interval
12|STRIKE_PRICE Strike price|interval
13|PREMIUM|interval (can be negative)
14|RECOVERY_PRICE Recovery price|interval
15|IMPLIED_VOLATILITY|interval
16|LEVERAGE_RATIO|interval
17|PRICE_RECOVERY_RATIO Underlying distance to recovery price %|interval
18|DELTA|interval
19|STATUS Warrant status|choice: 0=Normal, 1=Suspended, 2=Pre-IPO
20|IPO_TIME Listing time (timestamp seconds)|interval
21 / 22|BUY_VOL / SELL_VOL Bid / Ask volume|interval
23|EFFECTIVE_LEVERAGE|interval
24|LAST_CLOSE_PRICE Previous close|interval
25|TURNOVER|interval
26 / 27|SELL_PRICE / BUY_PRICE|interval
28 / 29|HIGH_PRICE / LOW_PRICE|interval
30|RATIO_ITM_OTM In/Out of the money|interval (can be negative)
31|BREAK_EVEN_POINT|interval
32|AMPLITUDE|interval
33|SCORE_FAXING SG score|interval
34|LAST_TRADE_DATE Last trade date (timestamp seconds)|interval
35|STREET_VOLUME Street volume|interval
36|LOT_SIZE Lot size|interval
37|ISSUE_SIZE Issue size|interval
38|IPO_PRICE IPO price|interval
39 / 40|LOWER_STRIKE_PRICE / UPPER_STRIKE_PRICE|interval (Inline only)
41|IW_PRICE_STATUS Inside / outside the range|choice
42|SENSITIVITY|interval
43|CONVERSION_PRICE Conversion price|interval
44 / 45|CHANGE_RATE / CHANGE_VALUE Change ratio / amount|interval
51|SCORE Composite score|interval
52|FILTER_NO_TRADE Filter out warrants with no trades|choice: 0=No, 1=Yes
53|CURRENCY_CODE Currency|choice
54|STOCK_OWNER_PRICE Underlying stock price|interval

## Warrant Screening V2 - WarrantMarket / WarrantType / WarrantStatus

> Common enums for `WarrantScreenRequest(warrant_market=...)` and `add_choice_filter`.

* **`WarrantMarket`**

    market|Meaning
    :-|:-
    1|HK Hong Kong
    4|SG Singapore
    15|MY Malaysia

* **`WarrantType`** (choice values for field_id=6)

    value|Meaning
    :-|:-
    1|CALL
    2|PUT
    3|BULL
    4|BEAR
    5|INLINE

* **`WarrantStatus`** (choice values for field_id=19)

    value|Meaning
    :-|:-
    0|NORMAL
    1|SUSPEND Suspended
    2|PRE_IPO Pre-IPO


## Option Market Type

> **OptionMarket**

* `UNKNOWN`

  Unknown

* `US_SECURITY`

  US Equity Options

* `US_INDEX`

  US Index Options

* `HK_SECURITY`

  HK Equity Options

* `HK_INDEX`

  HK Index Options

## Option Statistic Data Type

> **OptionStatisticDataType**

* `UNKNOWN`

  Unknown

* `VOLUME`

  Volume

* `OPEN_INTEREST`

  Open Interest

## Option HV Time Range

> **OptionHVTimeRange**

* `UNKNOWN`

  Unknown

* `THIRTY_DAY`

  30 Days

* `SIXTY_DAY`

  60 Days

* `NINETY_DAY`

  90 Days

* `ONE_TWENTY_DAY`

  120 Days

* `THREE_SIXTY_FIVE_DAY`

  365 Days

## Option Rank Type

> **OptionRankType**

* `UNKNOWN`

  Unknown

* `VOLUME`

  Volume

* `TURNOVER`

  Turnover

* `OI`

  Open Interest

* `OI_INCREMENT`

  OI Increment (Daily)

* `OI_DECREMENT`

  OI Decrement (Daily)

* `OI_MARKET_CAP`

  OI Market Cap

* `OI_MARKET_CAP_INCREMENT`

  OI Market Cap Increment (Daily)

* `OI_MARKET_CAP_DECREMENT`

  OI Market Cap Decrement (Daily)

* `CHANGE_RATE`

  Change Rate

* `IV`

  Implied Volatility

## Zero DTE Sort Type

> **ZeroDteSortType**

* `UNKNOWN`

  Unknown

* `VOLUME`

  Option Volume

* `IV`

  Implied Volatility

* `CHANGE_RATE`

  Change Rate

* `OPEN_INTEREST`

  Open Interest

* `MARKET_CAP`

  Market Cap

## Zero DTE Indicator Type

> **ZeroDteIndicatorType**

* `UNKNOWN`

  Unknown

* `OWNER_LIST`

  Watchlist

* `HAS_EARNINGS_THIS_WEEK`

  Has Earnings This Week (0=All, 1=Yes, 2=No)

* `VOLUME`

  Total Option Volume

* `OPEN_INTEREST`

  Total Open Interest

* `IV`

  Implied Volatility(%)

* `HV`

  Historical Volatility(%)

* `IV_RANK`

  IV Rank(%)

* `IV_PERCENTILE`

  IV Percentile(%)

* `PRICE`

  Last Price

* `CHANGE_RATE`

  Change Rate(%)

## Zero DTE Contract Sort Type

> **ZeroDteContractSortType**

* `UNKNOWN`

  Unknown

* `VOLUME`

  Volume

* `OPEN_INTEREST`

  Open Interest

* `IV`

  Implied Volatility

* `DELTA`

  Delta

## Zero DTE Contract Indicator Type

> **ZeroDteContractIndicatorType**

* `UNKNOWN`

  Unknown

* `OPTION_TYPE`

  Option Direction (1=Call, 2=Put)

* `VOLUME`

  Volume

* `OPEN_INTEREST`

  Open Interest

* `IV`

  Implied Volatility(%)

* `DELTA`

  Delta

* `GAMMA`

  Gamma

* `THETA`

  Theta

* `VEGA`

  Vega

* `RHO`

  Rho

* `PRICE`

  Last Price

* `CHANGE_RATE`

  Change Rate(%)

* `BREAK_EVEN_POINT`

  Break Even Point

* `TO_BEP`

  Distance to BEP(%)

* `BUY_PROFIT_PROBABILITY`

  Buy Profit Probability(%)

* `SELL_PROFIT_PROBABILITY`

  Sell Profit Probability(%)

## Earnings Sort Type

> **EarningsSortType**

* `UNKNOWN`

  Unknown

* `EARNINGS_DATE`

  Earnings Date (Default)

* `VOLUME`

  Option Volume

* `IV`

  Implied Volatility

* `MARKET_CAP`

  Market Cap

* `CHANGE_RATIO`

  Change Rate

* `PRICE`

  Last Price

* `IV_RANK`

  IV Rank

* `IV_PERCENTILE`

  IV Percentile

* `HV`

  Historical Volatility

* `OPEN_INTEREST`

  Open Interest

* `LAST_REPORT_IV_CRUSH`

  Last IV Crush

* `HISTORY_REPORT_IV_CRUSH`

  Historical IV Crush

* `LAST_REPORT_CHG_RATIO`

  Last Earnings Day Change

* `HISTORY_REPORT_CHG_RATIO`

  Historical Earnings Day Change

* `ESTIMATE_EPS_YOY`

  Estimated EPS YoY

* `ESTIMATE_REVENUE_YOY`

  Estimated Revenue YoY

* `EXPECTED_MOVE_RATIO`

  Expected Move

## Stock Category

> **StockCategory**

* `ALL`

  All

* `EQUITY`

  Equity

* `ETF`

  ETF

## Earnings Publication Type

> **EarningsPubType**

* `UNKNOWN`

  Unknown

* `BEFORE`

  Pre-market

* `AFTER`

  After-hours

## Earnings Indicator Type

> **EarningsIndicatorType**

* `UNKNOWN`

  Unknown

* `OWNER_LIST`

  Watchlist

* `INDEX_COMPONENT`

  Index Component

* `PLATE`

  Industry/Sector

* `MARKET_CAP`

  Market Cap

* `EXPIRATION_TYPE`

  Expiration Type

* `IV`

  Implied Volatility(%)

* `LAST_REPORT_IV_CRUSH`

  Last IV Crush(%)

* `HISTORY_REPORT_IV_CRUSH`

  Historical IV Crush(%)

* `IV_RANK`

  IV Rank(%)

* `IV_PERCENTILE`

  IV Percentile(%)

* `VOLUME`

  Option Volume

* `OPEN_INTEREST`

  Open Interest

* `PRICE`

  Last Price

* `CHANGE_RATIO`

  Change Rate(%)

* `EXPECTED_MOVE_RATIO`

  Expected Move(%)

* `LAST_REPORT_CHG_RATIO`

  Last Earnings Day Change(%)

* `HISTORY_REPORT_CHG_RATIO`

  Historical Earnings Day Change(%)

* `ESTIMATE_REVENUE_YOY`

  Estimated Revenue YoY(%)

* `ESTIMATE_EPS_YOY`

  Estimated EPS YoY(%)

* `EARNINGS_DAY_RANGE`

  Days to Earnings

## Seller Type

> **SellerType**

* `UNKNOWN`

  Unknown

* `COVERED_CALL`

  Covered Call

* `CASH_SECURED_PUT`

  Cash Secured Put

## Seller Sort Type

> **SellerSortType**

* `UNKNOWN`

  Unknown

* `ANNUALIZED_RETURN`

  Annualized Return (Default)

* `INTERVAL_RETURN`

  Interval Return

* `ITM_PROBABILITY`

  ITM Probability

* `PREMIUM`

  Premium

## Seller Indicator Type

> **SellerIndicatorType**

* `UNKNOWN`

  Unknown

* `OWNER_LIST`

  Watchlist

* `STOCK_CATEGORY`

  Stock Category

* `VOLUME`

  Total Option Volume

* `OPEN_INTEREST`

  Total Open Interest

* `IV`

  Underlying IV(%)

* `HV`

  Underlying HV(%)

* `IV_RANK`

  IV Rank(%)

* `IV_PERCENTILE`

  IV Percentile(%)

* `MARKET_CAP`

  Market Cap

* `PRICE`

  Last Price

* `CHANGE_RATE`

  Change Rate(%)

* `PLATE`

  Sector

* `EXPIRATION_TYPE`

  Expiration Type

* `LEFT_DAYS`

  Days to Expiry

* `OPTION_TYPE`

  Option Direction (1=Call, 2=Put)

* `OPTION_EXPIRATION_TYPE`

  Option Expiration Type

* `STRIKE_DATE_TIMESTAMP`

  Expiry Date Timestamp (sec)

* `PREMIUM`

  Premium

* `ANNUALIZED_RETURN`

  Annualized Return(%)

* `INTERVAL_RETURN`

  Interval Return(%)

* `OTM_DEGREE`

  OTM Degree(%)

* `OTM_PROBABILITY`

  OTM Probability(%)

* `OPTION_IV`

  Option IV(%)

* `BID_PRICE`

  Bid Price

* `ASK_PRICE`

  Ask Price

* `OPTION_VOLUME`

  Option Volume

* `OPTION_OPEN_INTEREST`

  Option Open Interest

## Underlying Rank Sort Type

> **UnderlyingRankSortType**

* `UNKNOWN`

  Unknown

* `VOLUME`

  Total Volume

* `VOLUME_RATIO`

  Put/Call Volume Ratio

* `OPEN_INTEREST`

  Total Open Interest

* `OPEN_INTEREST_RATIO`

  Put/Call OI Ratio

* `PRICE`

  Last Price

* `PRICE_CHANGE`

  Change Rate

* `IV`

  IV

* `IV_CHANGE`

  IV Change

* `HV`

  HV

* `HV_CHANGE`

  HV Change

* `IV_RANK`

  IV Rank

* `IV_PERCENTILE`

  IV Percentile

* `MARKET_CAP`

  Market Cap

## Underlying Rank Indicator Type

> **UnderlyingRankIndicatorType**

* `UNKNOWN`

  Unknown

* `OWNER_LIST`

  Watchlist

* `STOCK_CATEGORY`

  Stock Category

* `VOLUME`

  Total Volume

* `OPEN_INTEREST`

  Total Open Interest

* `IV`

  IV(%)

* `HV`

  HV(%)

* `IV_RANK`

  IV Rank(%)

* `IV_PERCENTILE`

  IV Percentile(%)

* `IV_CHANGE`

  IV Change(%)

* `HV_CHANGE`

  HV Change(%)

* `VOLUME_RATIO`

  Volume P/C Ratio(%)

* `OI_RATIO`

  OI P/C Ratio(%)

* `MARKET_CAP`

  Market Cap

* `PRICE`

  Last Price

* `CHANGE_RATE`

  Change Rate(%)

## Option Rank Indicator Type

> **OptionRankIndicatorType**

* `UNKNOWN`

  Unknown

* `STOCK_CATEGORY`

  Stock Category

* `MARKET_CAP`

  Market Cap

* `OWNER_LIST`

  Watchlist

* `UNDERLYING_IV`

  Underlying IV(%)

* `UNDERLYING_HV`

  Underlying HV(%)

* `IV_RANK`

  IV Rank(%)

* `IV_PERCENTILE`

  IV Percentile(%)

* `IV`

  Implied Volatility(%)

* `OPTION_TYPE`

  Direction (Call/Put)

* `LEFT_DAYS`

  Days to Expiry

* `IN_THE_MONEY`

  ITM/OTM (0=OTM, 1=ITM)

* `VOLUME`

  Volume

* `OPEN_INTEREST`

  Open Interest

* `DELTA`

  Delta

* `GAMMA`

  Gamma

* `THETA`

  Theta

* `VEGA`

  Vega

* `RHO`

  Rho

## Expiration Type

> **ExpirationType**

* `UNKNOWN`

  Unknown

* `MONTHLY`

  Monthly

* `WEEKLY`

  Weekly

* `END_OF_MONTH`

  End of Month

* `QUARTERLY`

  Quarterly

## Index Component Type

> **IndexComponentType**

* `UNKNOWN`

  Unknown

* `DJI`

  Dow Jones

* `IXIC`

  NASDAQ Composite

* `NDX`

  NASDAQ 100

* `SPX`

  S&P 500

## Option Event Ticker Direction

> **EventTickerType**

* `UNKNOWN`

  Unknown

* `BUY`

  Active Buy

* `SELL`

  Active Sell

* `NEUTRAL`

  Neutral

## Option Event Order Type

> **AlertOrderType**

* `NORMAL`

  Normal Order

* `SWEEP`

  Sweep

* `CROSS`

  Cross

* `FLOOR`

  Floor

## Strategy Type

> **TickerStrategy**

* `UNKNOWN`

  Unknown

* `SINGLE_LEG`

  Single Leg

* `MULTI_LEG`

  Multi Leg

## Market Sentiment

> **MarketSentiment**

* `UNKNOWN`

  Unknown

* `BEARISH`

  Bearish

* `BULLISH`

  Bullish

* `NEUTRAL`

  Neutral

## Corporate Action Type

> **CorporateActionType**

* `NONE`

  None/Unknown

* `SPLIT`

  Stock Split

* `JOIN`

  Reverse Split

* `BONUS_STOCK`

  Bonus Share

* `INTO_SHARES`

  Bonus Issue

* `ALLOT`

  Rights Issue

* `ADD`

  Additional Issuance

* `DIVIDEND`

  Dividend

* `SPECIAL_DIVIDEND`

  Special Dividend

* `SPIN_OFF`

  Spin Off

## In/Out of The Money Type

> **InTheMoneyType**

* `UNKNOWN`

  Unknown

* `IN`

  In The Money (ITM)

* `OUT`

  Out of The Money (OTM)

## Event Indicator Type

> **EventIndicatorType**

* `OWNER_LIST`

  Underlying list (security_list)

* `INDUSTRY_PLATE`

  Industry plate list (security_list)

* `CONCEPT_PLATE`

  Concept plate list (security_list)

* `CORPORATE_ACTION`

  Corporate action type (value_list, CorporateActionType)

* `MARKET_CAP`

  Market cap (range)

* `OPTION_TYPE`

  CALL(1)/PUT(2) (value_list)

* `MONEY_TYPE`

  ITM(1)/OTM(2) (value_list)

* `STRIKE_PRICE`

  Strike price (range)

* `EXPIRY_DAYS`

  Days to expiry (range)

* `OTM`

  OTM ratio (%) (range)

* `TICKER_TYPE`

  Ticker direction (value_list, EventTickerType)

* `VOLUME`

  Volume (range)

* `TURNOVER`

  Turnover (range)

* `PRICE`

  Price (range)

* `TIME`

  Event time (range, Unix seconds)

* `MAX_DAY_NUM`

  Day range (value_list, 0=today, 1=last 2 days ...)

* `ORDER_TYPE`

  Order type (value_list, AlertOrderType)

* `STRATEGY`

  Strategy type (value_list, TickerStrategy)

* `SENTIMENT`

  Market sentiment (value_list, MarketSentiment)

* `TOTAL_VOLUME`

  Total option volume (range)

* `TOTAL_OI`

  Total open interest (range)

* `VO_RATIO`

  Volume/OI ratio (%) (range)

* `IV`

  Implied volatility (%) (range)

* `DELTA`

  Delta (range)

* `GAMMA`

  Gamma (range)

* `VEGA`

  Vega (range)

* `THETA`

  Theta (range)

* `RHO`

  Rho (range)

## Alert Operation Type

> **AlertOpType**

* `UNKNOWN`

  Unknown

* `ADD`

  Add

* `DELETE`

  Delete

* `MODIFY`

  Modify

* `ENABLE`

  Enable

* `DISABLE`

  Disable

* `DELETE_ALL`

  Delete All

---

# Overview

<table>
    <tr>
        <th>Module</th>
        <th>Interface Name</th>
        <th>Function Description</th>
    </tr>
    <tr>
        <td rowspan="2">Account</td>
	    <td><a href="./get-acc-list.html">get_acc_list</a></td>
	    <td>Get account list</td>
    </tr>
    <tr>
	    <td><a href="./unlock.html">unlock_trade</a></td>
	    <td>Unlock trading</td>
    </tr>
    <tr>
        <td rowspan="6">Asset and Position</td>
	    <td><a href="./get-funds.html">accinfo_query</a></td>
	    <td>Get account financial information</td>
    </tr>
    <tr>
	    <td><a href="./get-max-trd-qtys.html">acctradinginfo_query</a></td>
	    <td>Get maximum tradable quantity</td>
    </tr>
    <tr>
	    <td><a href="./comboorder-tradinginfo-query.html">comboorder_tradinginfo_query</a></td>
	    <td>Query combo tradable info</td>
    </tr>
    <tr>
	    <td><a href="./get-position-list.html">position_list_query</a></td>
	    <td>Get positions list</td>
    </tr>
    <tr>
        <td><a href="../trade/get-margin-ratio.html">Trd_GetMarginRatio</a></td>
        <td>Get margin data</td>
    </tr>
    <tr>
        <td><a href="../trade/get-acc-cash-flow.html">Get Cash Flow Summary</a></td>
	    <td>Get Account Cash Flow Data (Minimum version requirement：9.1.5108)</td>
    </tr>
    <tr>
        <td rowspan="8">Order</td>
	    <td><a href="./place-order.html">place_order</a></td>
	    <td>Place order</td>
    </tr>
    <tr>
	    <td><a href="./place-combo-order.html">place_combo_order</a></td>
	    <td>Place combo order</td>
    </tr>
    <tr>
	    <td><a href="./modify-order.html">modify_order</a></td>
	    <td>Modify or cancel order</td>
    </tr>
    <tr>
	    <td><a href="./get-order-list.html">order_list_query</a></td>
	    <td>Get order list</td>
    </tr>
	<tr>
	    <td><a href="./order-fee-query.html">order_fee_query</a></td>
	    <td>Get order fees (Minimum version requirement: 8.2.4218)</td>
    </tr>
    <tr>
	    <td><a href="./get-history-order-list.html">history_order_list_query</a></td>
	    <td>Get historical order list</td>
    </tr>
    <tr>
	    <td><a href="./update-order.html">TradeOrderHandlerBase</a></td>
	    <td>Order callback</td>
    </tr>
    <tr>
	    <td><a href="./sub-acc-push.html">SubAccPush</a></td>
	    <td>Trade data callback</td>
    </tr>
    <tr>
        <td rowspan="3">Deal</td>
	    <td><a href="./get-order-fill-list.html">deal_list_query</a></td>
	    <td>Get today's executed trades</td>
    </tr>
    <tr>
	    <td><a href="./get-history-order-fill-list.html">history_deal_list_query</a></td>
	    <td>Get historical executed trades</td>
    </tr>
    <tr>
	    <td><a href="./update-order-fill.html">TradeDealHandlerBase</a></td>
	    <td>Trade execution callback</td>
    </tr>
</table>

---

# Transaction Objects

## Create the connection

`OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)`  
  
`OpenFutureTradeContext(host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)` 

`OpenCryptoTradeContext(host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)` 

* **Description**

    According to the transaction variaties, select a correct account, and create its transaction object.
    Transaction Objects | Accounts
    :-|:-
    OpenSecTradeContext|Securities account  (Trading stocks, ETFs, warrants, stock options or index options uses this account.)
    OpenFutureTradeContext|Futures account  (Trading futures or future options uses this account.)
    OpenCryptoTradeContext|Cryptocurrency account  (- Used for cryptocurrency spot trading
  - Only supports FUTUSECURITIES, FUTUINC, FUTUSG
  - Simulated trading is not supported)


* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    filter_trdmarket|[TrdMarket](./trade.html#6257)|Filter accounts according to the transaction market authority.  (- This parameter is only available for OpenSecTradeContext.
  - This parameter is only used to filter accounts and will not affect transaction connections.)
    host|str|The IP listened by OpenD.
    port|int|The port listened by OpenD.
    is_encrypt|bool|Whether to enable encryption.  (Default None means: use the setting of [enable_proto_encrypt](../ftapi/init.md#7910).)
    security_firm|[SecurityFirm](./trade.md#9434)|Specified security firm  (OpenCryptoTradeContext only supports FUTUSECURITIES, FUTUINC, FUTUSG)

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)
trd_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

```python
from moomoo import *
future_ctx = OpenFutureTradeContext(host='127.0.0.1', port=11111, security_firm=SecurityFirm.NONE)
future_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

```python
from moomoo import *
crypto_ctx = OpenCryptoTradeContext(host='127.0.0.1', port=11111, security_firm=SecurityFirm.NONE)
crypto_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```


## Close the connection

`close()`

* **Description**

    Close the trading object. By default, the threads created inside the moomoo API will prevent the process from exiting, and the process can exit normally only after all Contexts are closed. But through [set_all_thread_daemon](../ftapi/init.md#5242), all internal threads can be set as daemon threads. At this time, even if close of Context is not called, the process can exit normally.

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.NONE)
trd_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

---

# Get the List of Trading Accounts

`get_acc_list()`

* **Description**

    Get a list of trading accounts.
    Before calling other trading interfaces, please obtain this list first and confirm that the trading account to be operated is correct.

* **Parameters**
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, trading account list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Trading account list format as follows: 
        Field|Type|Description
        :-|:-|:-
        acc_id|int|Trading account.
        trd_env|[TrdEnv](./trade.md#48)|Trading environment.  
        acc_type|[TrdAccType](./trade.md#7166)|Account type.
        uni_card_num|str|Universal account number, same as the display in the mobile terminal.
        card_num|str|Trading account number (Under the Universal Account System, an Universal account contains one or more trading accounts(universal securities, universal futures, etc.), which is related to financing types.)
        sim_acc_type|[SimAccType](./trade.md#7358)|Simulate account type.  (For simulated accounts only.)
        security_firm|[SecurityFirm](./trade.md#9434)|Securities firm to which the account belongs.
        trdmarket_auth|list|Transaction market authority.  (Data type of elements in the list is [TrdMarket](./trade.html#6257).)
        acc_status|[TrdAccStatus](./trade.md#8311)|Account status.
        acc_role|[TrdAccRole](./trade.md#8663)|Account Structure  (Used to distinguish between master and normal account
  - MASTER: Master Account
  - NORMAL: Normal Account
  - IPO: Malaysian IPO account)
        jp_acc_type|list|JP sub account type  (Data type of elements in the list is [SubAccType](./trade.md#3947), Only applicable for Moomoo JP)

* **Description**

    To obtain the HK Paper Trading accounts, specify filter_trdmarket as TrdMarket.HK. This will return two paper trading accounts. The account with sim_acc_type = STOCK represents a HK paper trading account, while sim_acc_type = OPTION refers to a HK stock options paper trading account, and sim_acc_type = FUTURES indicates a HK futures paper trading account.  

    To obtain the US Paper Trading accounts, specify filter_trdmarket as TrdMarket.US. An account with sim_acc_type = STOCK_AND_OPTION represents the US margin paper trading account, which allows the stock and options trading. An account with sim_acc_type = FUTURES represents a US futures paper trading account.
    

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.get_acc_list()
if ret == RET_OK:
    print(data)
    print(data['acc_id'][0])  # Get the first account ID
    print(data['acc_id'].values.tolist())  # convert to list
else:
    print('get_acc_list error: ', data)
trd_ctx.close()
```

* **Output**

```python
               acc_id   trd_env acc_type       uni_card_num           card_num    security_firm   sim_acc_type                           trdmarket_auth    acc_status    acc_role    jp_acc_type
0  281756420273981734      REAL   MARGIN  10018561211263256   1001100530724347          FUTUINC            N/A    [HK, US, HKCC, SG, HKFUND, USFUND, JP]       ACTIVE      NORMAL             []
1             3450310  SIMULATE     CASH                N/A                N/A              N/A          STOCK                                      [HK]       ACTIVE         N/A             []
2             3548732  SIMULATE   MARGIN                N/A                N/A              N/A         OPTION                                      [HK]       ACTIVE         N/A             []
281756420273981734
[281756420273981734, 3450310, 3548732]
```

---

# Unlock Trade

`unlock_trade(password=None, password_md5=None, is_unlock=True)`

* **Description**

    Lock or unlock trade

* **Parameters**
    
    Parameter|Type|Description
    :-|:-|:-
    password|str|Transaction password.  (If password_md5 is not empty, use the passed password_md5 to unlock. Otherwise, MD5 calculated from password is used for password_md5 and then unlock.)
    password_md5|str|32-bit MD5 encryption of transaction password (all lowercase).  (A password must be filled in to unlock a transaction, and a locked transaction is ignored.)
    is_unlock|bool|Lock or unlock.  (True: unlock. False: lock.)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">msg</td>
            <td>NoneType</td>
            <td>If ret == RET_OK, None is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

        

* **Example**

```python
from moomoo import *
pwd_unlock = '123456'
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.unlock_trade(pwd_unlock)
if ret == RET_OK:
    print('unlock success!')
else:
    print('unlock_trade failed: ', data)
trd_ctx.close()
```

* **Output**

```python
unlock success!
```

:::tip
* When using live trading accounts, you need to **unlock trade** **before** calling *Place Order* or *Modify or Cancel Orders* interface, but when using paper trading accounts, you do not need to **unlock trade**.
* Locking or unlocking the transaction is an operation on OpenD. As long as one connection is unlocked, all other connections can call the transaction interface
* It is strongly recommended that customers who connect to OpenD via the external network for live trading use encrypted channels, refer to [Enable protocol encryption](../ftapi/init.md#7910)
* CLI API does not support moomoo token. If you have activated moomoo token, it will fail to unlock. You need to turn off the token and then use CLI API to unlock.
:::

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single user ID.
:::

---

# Get Account Funds

`accinfo_query(trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False, currency=Currency.HKD, asset_category=AssetCategory.NONE)`

* **Description**

    Query fund data such as net asset value, securities market value, cash, and purchasing power of trading accounts.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    trd_env|[TrdEnv](./trade.md#48)|Trading environment
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    refresh_cache|bool|Whether to refresh the cache.  (- True: Re-request data from the moomoo server immediately, without using the OpenD cache. At this time, it will be restricted by the interface frequency limit. 
  - False: Use OpenD's cache (The cache needs to be refreshed if it is not updated in rare circumstances.))
    currency|[Currency](./trade.md#1655)|The display currency of the funds.  (- Only applicable to universal securities accounts and futures accounts, other single-market accounts will ignore this parameter.
  - In the returned DataFrame, all fund-related fields can be converted with this parameter, except for the fields that explicitly specify the currency.)
    asset_category|[AssetCategory](./trade.md#2313)|Asset category  (Only applicable for Moomoo JP)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, fund data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Fund data format as follows: 
        Field|Type|Description
        :-|:-|:-
        power|float|Maximum Buying Power.  (- This field is the *approximate value* calculated according to the marginable initial margin of 50%. But in fact, this ratio of each financial contract is not the same. We recommend using ***Buy on margin***, returned by [Query the Maximum Quantity that Can be Bought or Sold](./get-max-trd-qtys.md), to get the maximum quantity can buy.)
        max_power_short|float|Short Buying Power.  (- This field is the *approximate value* calculated according to the shortable initial margin of 60%. But in fact, this ratio of each financial contract is not the same. We recommend using ***Short sell***, returned by [Query the Maximum Quantity that Can be Bought or Sold](./get-max-trd-qtys.md), to get the maximum quantity can be shorted.)
        net_cash_power|float|Cash Buying Power.  (Obsolete. Please use 'us_net_cash_power' or other fields to get the cash buying power of each currency.)
        total_assets|float|Total Net Assets. (Total Net Assets = Security Assets + Fund Assets + Bond Assets) 
        securities_assets|float|Security Assets (Minimum OpenD version requirements: 8.2.4218.)
        fund_assets|float|Fund Assets (- Universal accounts will return the total fund assets value. Currently, it does not support for HKD fund and USD fund assets value. 
  - Minimum OpenD version requirements: 8.2.4218.)
        bond_assets|float|Bond Assets (Minimum OpenD version requirements: 8.2.4218.)
        cash|float|Cash.  (Obsolete. Please use 'us_cash' or other fields to get the cash of each currency.)
        market_val|float|Securities Market Value.  (Only applicable to securities accounts.)
        long_mv|float|Long Market Value. 
        short_mv|float|Short Market Value. 
        pending_asset|float|Asset in Transit. 
        interest_charged_amount|float|Interest Charged Amount. 
        frozen_cash|float|Funds on Hold.
        avl_withdrawal_cash|float|Withdrawable Cash.  (Only applicable to securities accounts.)
        max_withdrawal|float|Maximum Withdrawal.  (- Only applicable to securities accounts of FUTU HK)
        currency|[Currency](./trade.md#1655)|The currency used for this query.  (Only applicable to universal securities accounts and futures accounts.)
        available_funds|float|Available funds.  (Only applicable to futures accounts.)
        unrealized_pl|float|Unrealized gain or loss.  (Only applicable to futures accounts.)
        realized_pl|float|Realized gain or loss.  (Only applicable to futures accounts.)
        risk_level|[CltRiskLevel](./trade.md#428)|Risk control level.  (Only applicable to futures accounts. It is recommanded to use exposure_level field to get the risk status of securities accounts or futures accounts.)
        risk_status|[CltRiskStatus](./trade.md#7469)| Risk status.  (- Applicable to securities accounts and futures accounts.
  - Divided into 9 grades, `LEVEL1` is the safest and `LEVEL9` is the most dangerous.)
        initial_margin|float|Initial Margin.  (- Only applicable to futures accounts.)
        margin_call_margin|float|Margin-call Margin. 
        maintenance_margin|float|Maintenance Margin. 
        hk_cash|float|HKD Cash.  (This field is the real value of this currency, instead of the value denominated in this currency.)
        hk_avl_withdrawal_cash|float|HKD Withdrawable Cash.  (This field is the real value of this currency, instead of the value denominated in this currency.)
        hkd_net_cash_power|float|HKD Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        hkd_assets|float|HK Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        us_cash|float|USD Cash.  (This field is the real value of this currency, instead of the value denominated in this currency.)
        us_avl_withdrawal_cash|float|USD Withdrawable Cash.  (This field is the real value of this currency, instead of the value denominated in this currency.)
        usd_net_cash_power|float|USD Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        usd_assets|float|US Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        cn_cash|float|CNH Cash.  (- Only applicable to universal securities accounts and futures accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency .)
        cn_avl_withdrawal_cash|float|CNH Withdrawable Cash.  (- Only applicable to universal securities accounts and futures accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency .)
        cnh_net_cash_power|float|CNH Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        cnh_assets|float|CN Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        jp_cash|float|JPY Cash.  (- This field is the real value of this currency, instead of the value denominated in this currency. 
  - Minimum Futu API version requirements: 5.8.2008)
        jp_avl_withdrawal_cash|float|JPY Withdrawable Cash.  (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum Futu API version requirements: 5.8.2008)
        jpy_net_cash_power|float|JPY Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        jpy_assets|float|JP Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        sg_cash|float|SGD Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency .)
        sg_avl_withdrawal_cash|float|SGD Withdrawable Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency .)
        sgd_net_cash_power|float|SGD Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        sgd_assets|float|SG Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        au_cash|float|AUD Cash.  (- Only applicable to universal securities accounts. 
  - Minimum Futu API version requirements: 5.8.2008)
        au_avl_withdrawal_cash|float|AUD Withdrawable Cash.  (- Only applicable to universal securities accounts. 
  - Minimum Futu API version requirements: 5.8.2008)
        aud_net_cash_power|float|AUD Cash Buying Power.   (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 8.7)
        aud_assets|float|AU Net Assets Value.   (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 9.0.5008)
        ca_cash|float|CAD Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        ca_avl_withdrawal_cash|float|CAD Withdrawable Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        cad_net_cash_power|float|CAD Cash Buying Power.  (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        cad_assets|float|CA Net Assets Value.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        my_cash|float|MYR Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        my_avl_withdrawal_cash|float|MYR Withdrawable Cash.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        myr_net_cash_power|float|MYR Cash Buying Power.  (- This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        myr_assets|float|MY Net Assets Value.  (- Only applicable to universal securities accounts.
  - This field is the real value of this currency, instead of the value denominated in this currency.
  - Minimum version requirements: 10.0.6008)
        is_pdt|bool|Is it marked as a PDT.  (True: It is a PDT.  False: Not a PDT.Only applicable to securities accounts of Moomoo US.Minimum OpenD version requirements: 5.8.2008.)
        pdt_seq|string|Day Trades Left.  (Only applicable to securities accounts of Moomoo US.Minimum OpenD version requirements: 5.8.2008.)
        beginning_dtbp|float|Beginning DTBP.  (Only applicable to securities accounts of Moomoo US marked as a PDT.Minimum OpenD version requirements: 5.8.2008.)
        remaining_dtbp|float|Remaining DTBP.  (Only applicable to securities accounts of Moomoo US marked as a PDT.Minimum OpenD version requirements: 5.8.2008.)
        dt_call_amount|float|Day-trading Call Amount.  (Only applicable to securities accounts of Moomoo US marked as a PDT.Minimum OpenD version requirements: 5.8.2008.)
        dt_status|[DtStatus](./trade.html#1018)|Day-trading Status.  (Only applicable to securities accounts of Moomoo US marked as a PDT.Minimum OpenD version requirements: 5.8.2008.)
        crypto_mv|float|Cryptocurrency market value
        exposure_level|[ExposureLevel](./trade.md#3662)|Exposure level status  (Crypto accounts return exposure statusSecurities/Futures accounts return risk status)
        exposure_limit|float|Exposure limit (in USD)  (Only for cryptocurrency accounts)
        used_limit|float|Used exposure limit (in USD)  (Only for cryptocurrency accounts)
        remaining_limit|float|Remaining exposure limit (in USD)  (Only for cryptocurrency accounts)

        
* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.accinfo_query()
if ret == RET_OK:
    print(data)
    print(data['power'][0])  # Get the first buying power
    print(data['power'].values.tolist())  # convert to list
else:
    print('accinfo_query error: ', data)
trd_ctx.close()  # Close the current connection
```

* **Output**

* **Output**

 ```python
power  max_power_short  net_cash_power  total_assets  securities_assets  fund_assets  bond_assets   cash   market_val      long_mv   short_mv  pending_asset  interest_charged_amount  frozen_cash  avl_withdrawal_cash  max_withdrawal currency available_funds unrealized_pl realized_pl risk_level risk_status  initial_margin  margin_call_margin  maintenance_margin  hk_cash  hk_avl_withdrawal_cash  hkd_net_cash_power  hkd_assets  us_cash  us_avl_withdrawal_cash  usd_net_cash_power  usd_assets  cn_cash  cn_avl_withdrawal_cash  cnh_net_cash_power  cnh_assets  jp_cash  jp_avl_withdrawal_cash  jpy_net_cash_power jpy_assets  sg_cash sg_avl_withdrawal_cash sgd_net_cash_power sgd_assets  au_cash au_avl_withdrawal_cash aud_net_cash_power aud_assets  ca_cash ca_avl_withdrawal_cash cad_net_cash_power cad_assets  my_cash my_avl_withdrawal_cash myr_net_cash_power myr_assets  is_pdt pdt_seq beginning_dtbp remaining_dtbp dt_call_amount dt_status
0  465453.903307    465453.903307             0.0   289932.0404        197028.2204     92903.82          0.0  25.18  197003.0448  211960.7568 -14957.712            0.0                      0.0    25.930845                  0.0             0.0      HKD             N/A           N/A         N/A        N/A      LEVEL3   219346.648525       288656.787955       181250.967601      0.0                     0.0          13225.7955     0.0   3.24                     0.0           9656.4365      0.0    0.0                     0.0                 0.0    0.0      0.0                     0.0                 0.0     0.0    N/A                    N/A                N/A     0.0    N/A                    N/A                N/A    0.0    N/A                    N/A                N/A    0.0    N/A                    N/A                N/A    0.0        N/A     N/A            N/A            N/A            N/A       N/A
465453.903307
[465453.903307]
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id)
* It will be restricted by the frequency limit for this interface, only when refresh_cache is True
:::

---

# Query the Maximum Quantity that Can be Bought or Sold

`acctradinginfo_query(order_type, code, price, order_id=None, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, session=Session.NONE, jp_acc_type=SubAccType.JP_GENERAL, position_id=NONE)`

* **Description**

    Query the maximum quantity that can be bought or sold under a specifictrading account, and you can also query the maximum changeable quantity of a specific order under a specifictrading account.

    Cash account request options are not supported.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    order_type|[OrderType](./trade.md#245)|Order type. 
    code|str|Security code.  (If it is a future main code, it will be automatically converted to the corresponding actual contract code.)
    price|float|Quotation.  (- Accuracy to 3 decimal places for securities account, and the excess part will be discarded.
  - Accuracy to 9 decimal places for futures account, and the excess part will be discarded.)
    order_id|str|Order ID.  (- The default is None, and the query is the maximum quantity that can be bought or sold of the new order. 
  - If you want to modify order, the order number must be sent. At this time, when calculating, the maximum quantity that can be changed for this order will be returned. 
  - If you use this parameter to query the maximum changeable quantity of an order, you need to call this interface more than 0.5 seconds after the order is placed.)
    adjust_limit|float|Price adjustment range.  (OpenD will automatically adjust the incoming price to the legal price.(Futures will ignore this parameter.)
  - A positive number represents an upward adjustment, and a negative number represents a downward adjustment. 
  - For example: 0.015 means upward adjustment and the amplitude does not exceed 1.5%; -0.01 means downward adjustment and the amplitude does not exceed 1%. The default 0 means no adjustment.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    session|[Session](../quote/quote.md#8688)|US stocks Trading Session  (Applied to US stocks, RTH, ETH, OVERNIGHT, ALL can be allowed.)
    jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)
    position_id|int|Position ID  (- Applicable for querying Sell and Buyback in Moomoo JP Derivative accounts.
  - It can be obtained by [Get Positions](./get-position-list.md) interface.)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, account list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Account list format as follows: 
        Field|Type|Description
        :-|:-|:-
        max_cash_buy|float|Buy on cash.  (-  Maximum quantity that can be bought in cash. 
  -  The unit of options is "contract".
  - Futures accounts are not applicable.)
        max_cash_and_margin_buy|float|Buy on margin.  (-  Maximum quantity that can be bought on margin. 
  -  The unit of options is "contract".
  - Futures accounts are not applicable.)
        max_position_sell|float|Sell on position.  (-  Maximum quantity can be sold. 
  -  The unit of options is "contract".) 
        max_sell_short|float|Short sell.  (-  Maximum quantity can be shorted.
  -  The unit of options is "contract".
  - Futures accounts are not applicable.) 
        max_buy_back|float|Short positions.  (- Buyback required quantity to close a position. When holding short positions, you must first buy back the short positions before you can continue to buy long.
  -  The unit of options and futures is "contract".)
        long_required_im|float|Initial margin change when buying one contract of an asset.  (-  Currently only futures and options apply.
  - No position: Returns the initial margin needed to buy one contract (a positive value).   
  - Long position: Returns the initial margin required to buy one contract (a positive value).  
  - Short position: Returns the initial margin released for buying back one contract (a negative value).)
        short_required_im|float|Initial margin change when selling one contract of an asset.  (-  Currently only futures and options apply.
  - No position: Returns the initial margin needed to short one contract (a positive value).   
  - Long position: Returns the initial margin released for selling one contract (a negative value).  
  -  Short position: Returns the initial margin needed to short one contract (a positive value).)
        session|[Session](../quote/quote.md#8688)|Order session (Only applied to US stocks)

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.acctradinginfo_query(order_type=OrderType.NORMAL, code='US.AAPL', price=400)
if ret == RET_OK:
    print(data)
    print(data['max_cash_and_margin_buy'][0])  # Get maximum quantity that can be bought on margin
else:
    print('acctradinginfo_query error: ', data)
trd_ctx.close()  # Close the current connection
```

* **Output**

```python
    max_cash_buy  max_cash_and_margin_buy  max_position_sell  max_sell_short  max_buy_back long_required_im short_required_im   session
0           0.0                   1500.0                0.0             0.0           0.0              N/A               N/A           N/A 
1500.0
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
:::

:::tip Tips
* Cash accounts do not support trading derivatives, so querying the maximum bp for options through cash accounts is not supported.
* Crypto only supports cash accounts trading, so querying the margin bp for crypto accounts is not supported.
* Maximum quantity that can be bought for futures should be calculated by yourself. The formula is floor(Max buying power/Initial margin change when buying one contract of an asset). Max buying power is from [Get Account Funds](./get-funds.md).
:::

---

# Query Combo Order Tradable Info

`comboorder_tradinginfo_query(combo_leg_list, price, qty, order_type=OrderType.NORMAL, order_id=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0)`

* **Description**

    Query tradable info for a combo order at the given price and quantity (e.g. margin and buying power changes). You can also pass an order ID to query tradable info for order modification.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    combo_leg_list|list|Combo leg list  (- Each element is a ComboLeg object; see the ComboLeg table in [place_combo_order](./place-combo-order.md))
    price|float|Quoted price  (For auction or market orders, also provide a current price so the server can calculate)
    qty|float|Quantity  (Combo quantity; actual quantity per leg is qty × that leg's qty_ratio)
    order_type|[OrderType](./trade.md#4181)|Order type
    order_id|str|Order ID  (- Default None queries tradable info for a new order
  - For order modification, pass server order ID orderIDEx to get related modifiable info)
    trd_env|[TrdEnv](./trade.md#6374)|Trading environment
    acc_id|int|Trading account ID  (- Either acc_id or acc_index; acc_id is recommended
  - When acc_id is 0, the account specified by acc_index is used)
    acc_index|int|Account index in the trading account list  (Defaults to 0, meaning the first trading account)

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, tradable info is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Tradable info format as follows:
        Field|Type|Description
        :-|:-|:-
        nlv_change|float|Net liquidation value change
        initial_margin_change|float|Initial margin change
        maintenance_margin_change|float|Maintenance margin change
        option_bp|float|Option buying power
        max_withdraw_change|float|Max withdrawable change
        bp_decrease|float|Buying power decrease

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
leg1 = ComboLeg()
leg1.code = 'US.AAPL260529C302500'
leg1.trd_side = TrdSide.BUY
leg1.qty_ratio = 1
leg2 = ComboLeg()
leg2.code = 'US.AAPL'
leg2.trd_side = TrdSide.SELL
leg2.qty_ratio = 100
combo_legs = [leg1, leg2]
ret, data = trd_ctx.comboorder_tradinginfo_query(combo_legs, price=100, qty=1, order_type=OrderType.NORMAL, trd_env=TrdEnv.SIMULATE)
if ret == RET_OK:
    print(data)
else:
    print('comboorder_tradinginfo_query error: ', data)
trd_ctx.close()
```

* **Output**

```python
   nlv_change  initial_margin_change  maintenance_margin_change  option_bp  max_withdraw_change  bp_decrease
0        ...                    ...                        ...        ...                  ...          ...
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id) for max tradable quantity query APIs.
:::

---

# Get Positions

`position_list_query(code='', position_market=TrdMarket.NONE, pl_ratio_min=None, pl_ratio_max=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False, asset_category=AssetCategory.NONE, currency=Currency.USD, show_option_strategy_view=False)`

* **Description**

    Query the holding position list of a specific trading account

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Security symbol.  (- Only return orders whose related security symbols correspond to these codes. If this parameter is not passed, return all. 
  - Note: For the code filtering of futures positions, you need to pass the contract code with a specific month, and it cannot be filtered by the future main contract code.)
    position_market| [TrdMarket](./trade.md#6257)|Filter positions by market. (- Return positions for the specified market.
  - If this parameter is not passed, return positions for all markets.)
    pl_ratio_min|float|The lower limit of the current gain or loss ratio filter.  (The securities account uses profit ratio on the diluted cost price, while the futures account uses the profit rate on the average cost price.For example: when 10 is passed, the positions with gain or loss ratio greater than +10% will be returned.)
    pl_ratio_max|float|The upper limit of the current gain or loss ratio filter.  (The securities account uses profit ratio on the diluted cost price, while the futures account uses the profit rate on the average cost price.For example: when 10 is passed, the positions with gain or loss ratio less than +10% will be returned.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.  
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    refresh_cache|bool|Whether to refresh the cache.  (- True: Re-request data from the Futu server immediately, without using the OpenD cache. At this time, it will be restricted by the interface frequency limit. 
  - False: Use OpenD's cache (The cache needs to be refreshed if it is not updated in rare circumstances.)
    asset_category|[AssetCategory](./trade.md#2313)|Asset category  (Only applicable for Moomoo JP)
    currency|[Currency](./trade.md#1655)|Currency unit for position data  (Only for crypto accounts)
    show_option_strategy_view|bool|Whether to return option strategy view positions.  (- True: Returns positions in option strategy dimension (includes combo strategy fields).
  - False: Returns positions in symbol dimension (default).)


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, list of positions is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * List of positions format as follows: 
        Field|Type|Description
        :-|:-|:-
        position_side|[PositionSide](./trade.md#7930)|Position direction. 
        code|str|Security code.
        stock_name|str|Security name.
        position_market|[TrdMarket](./trade.md#6257)|Position market.
        qty|float|The number of holdings.  (The unit of options and futures is "contract".)
        can_sell_qty|float|Available quantity.  (Available quantity = Holding quantity - Frozen quantityThe unit of options and futures is "contract".)
        currency|[Currency](./trade.md#1655)|Transaction currency.
        nominal_price|float|Market price.  (3 decimal place accuracy, excess part will be rounded.)
        cost_price|float|Diluted Cost (for securities account). Average Cost (for futures account). (It is recommended to use the fields of average_cost and diluted_cost to obtain the cost price)
        cost_price_valid|bool|Whether the cost price is valid.  (True: valid.False: invalid.)
        average_cost|float|Average cost price  (Not valid for securities paper trading accountsMinimum version requirement: 9.2.5208)
        diluted_cost|float|Diluted cost price  (Not valid for futures trading accountsMinimum version requirement: 9.2.5208)
        market_val|float|Market value.  (3 decimal places accuracy(2 decimal places for A-shares, and 0 decimal place for futures).)
        pl_ratio|float|Proportion of gain or loss(under diluted cost price)  (This field is in percentage form, so 20 is equavalent to 20%.Not applicable to futures.)
        pl_ratio_valid|bool|Whether the gain or loss ratio is valid.  (True: valid.False: invalid.)
        pl_ratio_avg_cost|float|Proportion of gain or loss(under average cost price)  (This field is in percentage form, so 20 is equavalent to 20%.Not applicable to futures.)
        pl_val|float|Gain or loss.  (3 decimal places accuracy(2 decimal places for A-shares).)
        pl_val_valid|bool|Whether the gain or loss is valid.  (True: valid.False: invalid.)
        today_pl_val|float|Gain or loss today.  (3 decimal places accuracy(2 decimal places for A-shares).)
        today_trd_val|float|Transaction amount today.  (Only valid in the real trading environment.3 decimal places accuracy(2 decimal places for A-shares). Not applicable to futures.)
        today_buy_qty|float|Total volume purchased today.  (Only valid in the real trading environment.3 decimal places accuracy(2 decimal places for A-shares).Not applicable to futures.) 
        today_buy_val|float|Total amount purchased today.  (Only valid in the real trading environment.3 decimal places accuracy(2 decimal places for A-shares).Not applicable to futures.) 
        today_sell_qty|float|Total volume sold today.  (Only valid in the real trading environment.3 decimal places accuracy(2 decimal places for A-shares).Not applicable to futures.) 
        today_sell_val|float|Total amount sold today.  (Only valid in the real trading environment.3 decimal places accuracy(2 decimal places for A-shares).Not applicable to futures.) 
        unrealized_pl|float|Unrealized gain or loss.  (Not valid for securities paper trading accountsIt is the unrealized profit and loss under the average cost price, for universal securities accounts) 
        realized_pl|float|Realized gain or loss.  (Not valid for securities paper trading accountsIt is the realized profit and loss under the average cost price, for universal securities accounts) 
        position_id|int|Position ID
        combo_id|int|Combo ID  (Valid when show_option_strategy_view=True)
        strategy_type|[OptionStrategyType](../quote/quote.md#2931)|Combo strategy type  (Valid when show_option_strategy_view=True)
        position_type|[PositionType](./trade.md#5179)|Position type  (Valid when show_option_strategy_view=True)
        acc_id|int|Trading account ID
        jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)

* **Example**

```python
from futu import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.position_list_query()
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the position list is not empty
        print(data['stock_name'][0])  # Get the first stock name of the holding position
        print(data['stock_name'].values.tolist())  # Convert to list
else:
    print('position_list_query error: ', data)
trd_ctx.close()  # Close the current connection
```

* **Output**

```python
       code stock_name position_market    qty  can_sell_qty  cost_price  cost_price_valid average_cost  diluted_cost  market_val  nominal_price  pl_ratio  pl_ratio_valid pl_ratio_avg_cost  pl_val  pl_val_valid today_buy_qty today_buy_val today_pl_val today_trd_val today_sell_qty today_sell_val position_side unrealized_pl realized_pl currency asset_category position_id
0  US.AAPL   Apple Inc.              US  400.0         400.0      53.975              True          53.975        53.975     19760.0           49.4 -8.476146            True            -8.476146    -1830.0          True           0.0           0.0          0.0           0.0            0.0            0.0          LONG           0.0         0.0      USD      N/A      6596101776329286054
Apple Inc.
['Apple Inc.']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
* Call this interface, only when the cache is refreshed, will it be restricted by the frequency limit
:::

---

# Get Margin Data

`get_margin_ratio(code_list)`

* **Description**

    Query the margin data of stocks.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code_list|list|Stock list.  (Up to 100 targets can be requested each time.Data type of elements in the list is str.)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, margin data is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Margin data format as follows: 
        Field|Type|Description
        :-|:-|:-
        code| str| Stock code
        is_long_permit|bool| Is marginable trading allowed.
        is_short_permit | bool | Is shortable trading allowed.
        short_pool_remain | float | Short pool remaining.  (unit: shares.)
        short_fee_rate | float | Borrow rate.  (This field is in percentage form, so 20 is equivalent to 20%.)
        alert_long_ratio | float | Marginable alert margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        alert_short_ratio | float | Shortable alert margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        im_long_ratio | float | Marginable initial margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        im_short_ratio | float | Shortable initial margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        mcm_long_ratio | float | Marginable margin call margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        mcm_short_ratio | float  | Shortable margin call margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        mm_long_ratio |float | Marginable maintenance margin.  (This field is in percentage form, so 20 is equivalent to 20%.)
        mm_short_ratio |float | Marginable maintenance margin.  (This field is in percentage form, so 20 is equivalent to 20%.)

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.get_margin_ratio(code_list=['US.AAPL','US.FUTU'])  
if ret == RET_OK:
    print(data)
	print(data['is_long_permit'][0])  # Get whether marginable trading allowed for the first stock
    print(data['im_short_ratio'].values.tolist())  # Convert to list
else:
    print('error:', data)
trd_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

* **Output**

```python
       code  is_long_permit  is_short_permit  short_pool_remain  short_fee_rate  alert_long_ratio  alert_short_ratio  im_long_ratio  im_short_ratio  mcm_long_ratio  mcm_short_ratio  mm_long_ratio  mm_short_ratio
0  US.AAPL             True             True          1826900.0            0.89              33.0               56.0           35.0            60.0            32.0             53.0           25.0            40.0
1  US.FUTU            True             True          1150600.0            0.95              48.0               46.0           50.0            50.0            47.0             43.0           40.0            30.0
True
[60.0, 50.0]
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single user ID.
* For each request, the maximum number of stocks supported by the parameter is 100.
* Stocks and ETFs of US, HK and A-share markets are supported.
:::

---

# Get Account Cash Flow

`get_acc_cash_flow(clearing_date='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, cashflow_direction=CashFlowDirection.NONE, start='', end='')`

* **Description**

    Query the cash flow list of a specified trading account on a specified date.
    This includes all transactions that affect cash balances, such as deposits/withdrawals, fund transfers, currency exchanges, buying/selling financial assets, margin interest, and securities lending interest.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    clearing_date|str|Clearing date.  (Required for Securities/Futures Account. Query each day separately with YYYY-MM-DD format (e.g.,'2017-06-20').)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.  
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    cashflow_direction|[CashFlowDirection](./trade.md#1384)| Filter by the direction of cash flow (e.g., inflow/outflow).
    start_time|str|Start time  (Only for cryptocurrency accounts, format: yyyy-MM-dd HH:mm:ss)
    end_time|str|End time  (Only for cryptocurrency accounts, format: yyyy-MM-dd HH:mm:ss)

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, account cash flow list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Account cash flow list format as follows: 
        Field|Type|Description
        :-|:-|:-
        cashflow_id|int|Cash flow ID
        clearing_date|str|Clearing date.
        settlement_date|str|Settlement date.
        currency|[Currency](./trade.md#1655)|Transaction currency.
        cashflow_type|str|Cash flow type.
        cashflow_direction|[CashFlowDirection](./trade.md#1384)|Cash flow direction.
        cashflow_amount|float|Cash flow amount (positive:inflow, negative:outflow).
        cashflow_remark|str|Remarks.

        
* **Example**

```python
from futu import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.get_acc_cash_flow(clearing_date='2025-02-18', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, cashflow_direction=CashFlowDirection.NONE)
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If account cash flow list is not empty
        print(data['cashflow_type'][0])  # Get direction of the first cash flow record
        print(data['cashflow_amount'].values.tolist())  # Convert to list
else:
    print('get_acc_cash_flow error: ', data)
trd_ctx.close()

```

* **Output**

```python
   cashflow_id     clearing_date     settlement_date     currency     cashflow_type     cashflow_direction     cashflow_amount     cashflow_remark
0  16308           2025-02-27        2025-02-28          HKD             Others                 N/A                   0.00      Opt ASS-P-JXC250227P13000-20250227
1  16357           2025-02-27        2025-03-03          HKD             Others                 OUT               -104000.00
2  16360           2025-02-27        2025-02-27          USD         Fund Redemption            IN                 23000.00     Fund Redemption#Taikang Kaitai US Dollar Money...      
3  16384           2025-02-27        2025-02-27          HKD         Fund Redemption            IN                104108.96     Fund Redemption#Taikang Kaitai Hong Kong Dolla...
Others
[0.00, -104000.00, 23000.00, 104108.96]
```


:::tip Interface Limitations
* A maximum of 20 requests per 30 seconds under a single account ID (acc_id).  
* Cash flows are arranged in chronological order.  
* Can not query cash flow list through paper trading accounts and moomoo US accounts.  
:::

---

# Place Orders

`place_order(price, qty, code, trd_side, order_type=OrderType.NORMAL, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, remark=None, time_in_force=TimeInForce.DAY,  fill_outside_rth=False, aux_price=None, trail_type=None, trail_value=None, trail_spread=None, session=Session.NONE, jp_acc_type=SubAccType.JP_GENERAL, position_id=NONE)`

* **Description**

    Place order
    :::tip Tips
    The Python API is synchronous, but the network transport is asynchronous. When the receiving time interval is very short between the response packet of  place_order and [Order Fill Push Callback](../trade/update-order-fill.md) or [Order Push Callback](../trade/update-order.md), it may happen that the response packet of place_order returns first, but the callback function is called first. For example: [Order Push Callback](../trade/update-order.md) may be called first, and then the place_order interface returns.
    :::

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    price|float|Order price.  (- When the order is a market order or auction order type, you still need to pass parameters, and price can be passed any value.
  - Precision:
  - Futures: 8 integer digits, 9 decimal places, supporting negative prices.
  - US stock options: 2 decimal places.
  - US stocks: less than $1, allowing 4 decimal places. Greater than or equal to $1, allowing 2 decimal places.
  - Others: 3 decimal places, round off excess digits.)
    qty|float|Order quantity.  (The unit of options and futures is "contract".)
    code|str|Code.  (If it is the future main code, it will be automatically converted to the actual corresponding contract code.)
    trd_side|[TrdSide](./trade.md#832)|Transaction direction.
    order_type|[OrderType](./trade.md#245)|Order type.
    adjust_limit|float|Price adjustment range.  (OpenD will automatically adjust the incoming price to the legal price. 
  -  Positive numbers represent upward adjustments, and negative numbers represent downward adjustments. 
  - For example: 0.015 means upward adjustment and the amplitude does not exceed 1.5%; -0.01 means downward adjustment and the amplitude does not exceed 1%. The default 0 means no adjustment.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    remark|str|Remark.  (The maximum length after converting to utf8 is 64 bytes. This remark field will be attached to the order to facilitate you to identify the order.)
    time_in_force|[TimeInForce](./trade.md#7678)|Valid period.  (Market orders of HK market, A-share market or global futures, only support *Day*)
    fill_outside_rth|bool|Whether allow to execute the order during pre-market or after-hours market trades. (Deprecated)  (This field has been deprecated. Recommended to use Session (trading session) for order placement.For HK pre-opening market and US pre/post-market. And market orders are only supported in regular trading hours.)
    aux_price|float|Trigger price.  (- If order type is Stop, Stop Limit, Market if Touched, or Limit if Touched, aux_price must be set.
  - Same as price. Round off excess digits.)
    trail_type|[TrailType](./trade.md#12)|Trailing type.  (If order type is Trailing Stop, or Trailing Stop Limit, trail_type must be set.)
    trail_value|float|Trailing amount/ratio.  (- If order type is Trailing Stop, or Trailing Stop Limit, trail_value must be set.
  - If the trail type is PERCENTAGE, this field is in percentage form, so 20 is equivalent to 20%. 
  - If the trail type is PRICE, same as price for integer places. For US stock options is fixed to 2 decimal places, while for US stocks it is 4; for others, same as price. Round off excess digits.
  - If the trail type is PERCENTAGE, this value will be rounded to 2 decimals. The integer places are same as price.)
    trail_spread|float|Specify spread.  (- If order type is Trailing Stop Limit, trail_spread must be set.
  - The price will be rounded to 3 decimals for securities account, and 9 decimals for futures account.)
    session|[Session](../quote/quote.md#8688)|US stocks Trading Session  (Applied to US stocks, RTH, ETH, OVERNIGHT, ALL can be allowed.)
    jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)
    position_id|int|Position ID  (- It is used for closing a position for Moomoo JP
  - It can be obtained by [Get Positions](./get-position-list.md) interface.)
    expire_time|str|Order expiry time, only valid when time_in_force is GTD

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        order_type|[OrderType](./trade.md#245)|Order type.
        order_status|[OrderStatus](./trade.md#8074)|Order status.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        qty|float|Order quantity.  (Option futures unit is "Contract".)
        price|float|Order price.  (3 decimal place accuracy, excess part will be rounded.)
        create_time|str|Create time.  (Format: yyyy-MM-dd HH:mm:ss
For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        updated_time|str|Last update time.  (Format: yyyy-MM-dd HH:mm:ss
For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).The unit of option futures is "Contract".) 
        dealt_qty|float|Deal quantity  (Option futures unit is "Contract".)
        dealt_avg_price|float|Average deal price.  (No precision limit.)
        last_err_msg|str|The last error description.  (If there is an error, the cause of the last error will be returned. If there is no error, an empty string will be returned.)
        remark|str|Identification of remarks when placing an order.  (Refer to remark in the [place_order](./place-order.md) interface parameters for details.)
        time_in_force|[TimeInForce](./trade.md#7678)|Valid period.
        fill_outside_rth|bool|Whether pre-market and after-hours are needed.  (For HK pre-opening market and US pre/post-market.True: need. False: not need.)
        session|[Session](../quote/quote.md#8688)|Order session (Only applied to US stocks)
        aux_price|float|Traget price.
        trail_type|[TrailType](./trade.md#12)|Trailing type.
        trail_value|float|Trailing amount/ratio.
        trail_spread|float|Specify spread.

* **Example**

```python
from moomoo import *
pwd_unlock = '123456'
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.unlock_trade(pwd_unlock)  # If you use a live trading account to place an order, you need to unlock the account first. The example here is to place an order on a paper trading account, and unlocking is not necessary.
if ret == RET_OK:
    ret, data = trd_ctx.place_order(price=510.0, qty=100, code="US.AAPL", trd_side=TrdSide.BUY, trd_env=TrdEnv.SIMULATE, session=Session.NONE)
    if ret == RET_OK:
        print(data)
        print(data['order_id'][0])  # Get the order ID of the placed order
        print(data['order_id'].values.tolist())  # Convert to list
    else:
        print('place_order error: ', data)
else:
    print('unlock_trade failed: ', data)
trd_ctx.close()
```

* **Output**

```python

       code stock_name trd_side order_type order_status           order_id    qty  price          create_time         updated_time  dealt_qty  dealt_avg_price last_err_msg remark time_in_force fill_outside_rth session aux_price trail_type trail_value trail_spread currency
0  US.AAPL       Apple Inc.      BUY     NORMAL   SUBMITTING  38196006548709500  100.0  420.0  2021-11-04 11:38:19  2021-11-04 11:38:19        0.0              0.0                               DAY              N/A       N/A    N/A      N/A         N/A          N/A      USD
38196006548709500
['38196006548709500']
```

:::tip Interface Limitations
* A maximum of 15 requests per 30 seconds under a single account ID (acc_id), and the interval between two consecutive requests cannot be less than 0.02 seconds. Shared frequency limit with [Place Combo Order](./place-combo-order.md).  
* When using live trading accounts, you need to [unlock trade](./unlock.md) **before** calling *Place Order* interface, but when using paper trading accounts, you do not need to [unlock trade](./unlock.md).
:::

:::tip Tips
* Required parameters for each order type: [Click here](../qa/trade.html#8229) to learn more.
* Each broker sets limits on shares or amounts for single orders of various trading products. Exceeding these limits may result in order failures: [Click here](../qa/trade.html#8229) to learn more.
* Locking position is not supported for **shortable securities**, that means you can not hold a long position and a short position at the same time.
* If you want to **close out position** of a **shortable securities**, you need to get the direction of the position and send an opposite order with the same quantity.
* If you want to **reversing trade** of a **shortable securities**, there are 2 steps: 1. you need to get the direction of the position and send an opposite order with the same quantity. 2. Send an opposite order again to open the reverse trade.
For example: If you want to reverse trade of 1 long position of HK.HSI2012, you need to close the long position first and then sell short the contract.
* Only limit orders can be allowed during US stocks 24 Hour Trading Hour. You can choose Day, Good-Till-Cancelled (GTC) as the time-in-force. 24-hour order runs from Sunday 8:00 PM to Friday 8:00 PM ET, covering regular trading hours plus pre-market, post-market, and overnight trading sessions. You can place orders anytime during this period.  
* Paper trading of US stocks does not support irregular trading hours (including pre/post-market and overnight).
:::

---

# Place Combo Order

`place_combo_order(combo_leg_list, price, qty, order_type=OrderType.NORMAL, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, remark="", time_in_force=TimeInForce.DAY, expire_time=None)`

* **Description**

    Submit combo option/combo strategy orders.
    :::tip Tips
    The Python API is synchronous, but the network transport is asynchronous. When the receiving time interval is very short between the response packet of place_combo_order and [Order Fill Push Callback](../trade/update-order-fill.md) or [Order Push Callback](../trade/update-order.md), it may happen that the response packet of place_combo_order returns first, but the callback function is called first.
    :::

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    combo_leg_list|list|Combo leg list  (- Each element is a ComboLeg object describing a security and trading direction in the combo
  - See the table below for ComboLeg fields)
    price|float|Order price  (- When the order is a market order or auction order type, you still need to pass price; any value is acceptable
  - Precision rules are the same as the price parameter in [place_order](./place-order.md))
    qty|float|Order quantity  (Combo order quantity; the actual quantity of each leg is qty × that leg's qty_ratio)
    order_type|[OrderType](./trade.md#4181)|Order type
    trd_env|[TrdEnv](./trade.md#6374)|Trading environment
    acc_id|int|Trading account ID  (- Either acc_id or acc_index can be used to specify the trading account; acc_id is recommended
  - When acc_id is 0, the account specified by acc_index is used
  - When acc_id is a non-zero ID, the account specified by acc_id is used)
    acc_index|int|Account index in the trading account list  (- Either acc_id or acc_index can be used to specify the trading account; acc_id is recommended
  - acc_index defaults to 0, meaning the first trading account)
    remark|str|Remark  (- The order carries this remark field to help you identify the order
  - Maximum length after converting to UTF-8 is 64 bytes)
    time_in_force|[TimeInForce](./trade.md#4241)|Valid period
    expire_time|str|Order expiry time  (Valid when time_in_force is GTD; format: yyyy-MM-dd)

    * ComboLeg object fields:
        Field|Type|Description
        :-|:-|:-
        code|str|Security code, e.g. US.AAPL、US.AAPL260529C302500
        trd_side|[TrdSide](./trade.md#5815)|Trading direction of this leg
        qty_ratio|float|Quantity ratio  (Actual quantity of this leg = order qty × qty_ratio)
        position_id|int|Position ID  (Required when closing a position. Use the position_id from the option strategy view returned by [Get Position List](./get-position-list.md) with show_option_strategy_view=True.)

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#7467"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows:
        Field|Type|Description
        :-|:-|:-
        order_id|str|Order ID
        code|str|Combo strategy code
        strategy_type|[OptionStrategyType](../quote/quote.md#2931)|Combo strategy type
        trd_side|[TrdSide](./trade.md#5815)|Trading direction
        order_type|[OrderType](./trade.md#4181)|Order type
        order_status|[OrderStatus](./trade.md#797)|Order status
        qty|float|Order quantity
        price|float|Order price
        amount|float|Order amount
        time_in_force|[TimeInForce](./trade.md#4241)|Valid period
        expire_time|str|Expiry time
        dealt_qty|float|Deal quantity
        dealt_avg_price|float|Average deal price
        create_time|str|Create time
        updated_time|str|Last update time
        last_err_msg|str|Last error description
        remark|str|Remark
        combo_legs|list|Combo leg list  (Elements are ComboLeg objects)

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
leg1 = ComboLeg()
leg1.code = 'US.AAPL260529C302500'
leg1.trd_side = TrdSide.BUY
leg1.qty_ratio = 1
leg2 = ComboLeg()
leg2.code = 'US.AAPL'
leg2.trd_side = TrdSide.SELL
leg2.qty_ratio = 100
combo_legs = [leg1, leg2]
ret, data = trd_ctx.place_combo_order(combo_legs, price=9.9, qty=1, order_type=OrderType.NORMAL, trd_env=TrdEnv.SIMULATE)
if ret == RET_OK:
    print(data)
    print(data['order_id'][0])
else:
    print('place_combo_order error: ', data)
trd_ctx.close()
```

* **Output**

```python
              order_id  code strategy_type trd_side order_type order_status  qty  price  ...
0  FH1C79E90941477000   ...           ...      ...     NORMAL   SUBMITTING  1.0  9.9  ...
FH1C79E90941477000
```

:::tip Interface Limitations
* A maximum of 15 requests per 30 seconds under a single account ID (acc_id), and the interval between two consecutive requests cannot be less than 0.02 seconds. Shared frequency limit with [Place Order](place-order.md).
* When using live trading accounts, you need to [unlock trade](./unlock.md) before calling the order placement interface; paper trading accounts do not require unlocking.
:::

:::tip Tips
* Securities in combo_leg_list must belong to the same trading market; the system determines trd_market based on the first leg's market.
* Each leg's qty_ratio and qty together determine the actual order quantity of each leg.
:::

---

# Modify or Cancel Orders

`modify_order(modify_order_op, order_id, qty, price, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, aux_price=None, trail_type=None, trail_value=None, trail_spread=None)`

* **Description**

    Modify the price and quantity of orders, cancel orders, delete orders, enable or disable orders, etc.  
    For HKCC market, it is invalid to change orders, except that cancelling orders is supported.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    modify_order_op|[ModifyOrderOp](./trade.md#3811)|Modify order operation type.
    order_id|str|Order ID.
    qty|float|The quantity after the order is changed.  (The unit of options and futures is "contract". 0 decimal place accuracy, the excess part is discarded.)
    price|float|The price after the order is changed.  (Accuracy to 3 decimal places for securities account, and the excess part will be discarded. Accuracy to 9 decimal places for futures account, and the excess part will be discarded.)
    adjust_limit|float|Price adjustment range.  (OpenD will automatically adjust the incoming price to the legal price.(This parameter will be ignored by future contracts.) 
  -  Positive numbers represent upward adjustments, and negative numbers represent downward adjustments. 
  - For example: 0.015 means upward adjustment and the amplitude does not exceed 1.5%; -0.01 means downward adjustment and the amplitude does not exceed 1%. The default 0 means no adjustment.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    aux_price|float|Trigger price.  (- If order type is Stop, Stop Limit, Market if Touched, or Limit if Touched, aux_price must be set.
  - The price will be rounded to 3 decimals for securities account, and 9 decimals for futures account.)
    trail_type|[TrailType](./trade.md#12)|Trailing type.  (If order type is Trailing Stop, or Trailing Stop Limit, trail_type must be set.)
    trail_value|float|Trailing amount/ratio.  (- If order type is Trailing Stop, or Trailing Stop Limit, trail_value must be set.
  - If the trail type is PERCENTAGE, this field is in percentage form, so 20 is equivalent to 20%. 
  - If the trail type is PRICE, this value will be rounded to 3 decimals for securities account, and 9 decimals for futures account.
  - If the trail type is PRICE, this value will be rounded to 2 decimals.)
    trail_spread|float|Specify spread.  (- If order type is Trailing Stop Limit, trail_spread must be set.
  - The price will be rounded to 3 decimals for securities account, and 9 decimals for futures account.)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, modification information is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Modification information format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_env|[TrdEnv](./trade.md#48)|Trading environment.
        order_id|str|Order ID.

* **Example**

```python
from moomoo import *
pwd_unlock = '123456'
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.unlock_trade(pwd_unlock)  # If you use a live trading account to modify or cancel an order, you need to unlock the account first. The example here is to cancel an order on a paper trading account, and unlocking is not necessary.
if ret == RET_OK:
    order_id = "8851102695472794941"
    ret, data = trd_ctx.modify_order(ModifyOrderOp.CANCEL, order_id, 0, 0)
    if ret == RET_OK:
        print(data)
        print(data['stock_name'][0])  # Get the order ID of the modified order
        print(data['stock_name'].values.tolist())  # Convert to list
    else:
        print('modify_order error: ', data)
else:
    print('unlock_trade failed: ', data)
trd_ctx.close()
```

* **Output**

```python
    trd_env             order_id
0    REAL      8851102695472794941
8851102695472794941
['8851102695472794941']
```


`cancel_all_order(trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, trdmarket=TrdMarket.NONE)`

* **Description**

    Cancel all orders. Paper trading and HKCC trading accounts do not support all cancellations.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    trd_env|[TrdEnv](./trade.md#48)|Trading environment. 
    acc_id|int|Trading account ID.  (When acc_id is 0, the account specified by acc_index is chosen.When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    trdmarket|[TrdMarket](./trade.html#6257)|Transaction market selection.  (Cancel orders in specified markets the given account.In the default state, cancel orders in all markets for the given account.)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td>int</td>
            <td>Returned value. On success, ret == RET_OK. On error, ret != RET_OK.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td rowspan="2">str</td>
            <td>If ret == RET_OK, modification information is returned.</td>
        </tr>
        <tr>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Modification information format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_env|[TrdEnv](./trade.md#48)|Trading environment 
        order_id|str|Order number

* **Example**

```python
from moomoo import *
pwd_unlock = '123456'
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.unlock_trade(pwd_unlock)  # If you use a live trading account to modify or cancel an order, you need to unlock the account first. The example here is to cancel all orders on a paper trading account, and unlocking is not necessary.
if ret == RET_OK:
    ret, data = trd_ctx.cancel_all_order()
    if ret == RET_OK:
        print(data)
    else:
        print('cancel_all_order error: ', data)
else:
    print('unlock_trade failed: ', data)
trd_ctx.close()
```

* **Output**

```python
success
```

:::tip Interface Limitations
* A maximum of 20 requests per 30 seconds under a single account ID (acc_id), and the time interval between two consecutive requests should not be less than 0.04 seconds.
* When using live trading accounts, you need to [unlock trade](./unlock.md) **before** calling *Modify or Cancel Orders* interface, but when using paper trading accounts, you do not need to [unlock trade](./unlock.md).
:::

:::tip Tip
* For the execution of **modify the order**, to learn more about the required parameters for each order type, please [click here](../qa/trade.html#2440).
* If you want to **modify the quantity of the order**, the parameter **qty** should be equal to the total quantity of the expected filled.  
For example:   
The quantity of an order is *N* shares, with *n* shares filled. For the unfilled *(N-n)* shares, if you want to cancel *x* shares, the parameter **modify_order_op** should be *NORMAL*, **qty** should be *(N-x)*.
![order_quantity](../../img/order_quantity_en.png)
* If you want to cancel an order, the parameter **modify_order_op** should be *CANCEL*.  
For example:  
The quantity of an order is *N* shares, with *n* shares filled. If you want to cancel the unfilled *(N-n)* shares, **modify_order_op** should be *CANCEL*, and **qty** and **price** will be ignored.
:::

---

# Get open Orders

`order_list_query(order_id="", order_market=TrdMarket.NONE, status_filter_list=[], code='', start='', end='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False)`

* **Description**

    Query the open order list of the specified trading account (including all open orders, filled or cancelled orders within 24h)

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    order_id|str|Order id.  (If specified, only return data for the specified order.No filtering by default, return all.)
    order_market|[TrdMarket](./trade.md#6257)|Filter orders by security market. (- Return open orders for the specified market.
  - If this parameter is not passed or the default NONE is used, return open orders for all markets.)
    status_filter_list|list|Order status filter conditions.  (Only return data for the specified order.No filtering by default, return all.Data type of elements in the list is [OrderStatus](./trade.md#8074).)
    code|str|Security symbol.  (Only return orders whose related security symbols correspond to these codes. If this parameter is not passed, return all.)
    start|str|Start time.  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    end|str|End time.  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment. 
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    refresh_cache|bool|Whether to refresh the cache.  (- True: Re-request data from the Futu server immediately, without using the OpenD cache. At this time, it will be restricted by the interface frequency limit.
  - False: Use OpenD's cache (The cache needs to be refreshed if it is not updated in rare circumstances.))
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        order_type|[OrderType](./trade.md#245)|Order type.
        order_status|[OrderStatus](./trade.md#8074)|Order status.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        order_market|[TrdMarket](./trade.md#6257)|Order market.
        qty|float|Order quantity.  (Option futures unit is "Contract")
        price|float|Order price.  (3 decimal place accuracy, excess part will be rounded.)
        currency|[Currency](./trade.md#1655)|Transaction currency.
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        updated_time|str|Last update time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).The unit of option futures is "Contract") 
        dealt_qty|float|Deal quantity  (Option futures unit is "Contract")
        dealt_avg_price|float|Average deal price.  (No precision limit)
        last_err_msg|str|The last error description.  (If there is an error, the cause of the last error will be returned. If there is no error, an empty string will be returned.)
        remark|str|Identification of remarks when placing an order.  (Refer to remark in the [place_order](./place-order.md) interface parameters for details.)
        time_in_force|[TimeInForce](./trade.md#7678)|Valid period.
        fill_outside_rth|bool|Whether pre-market and after-hours are needed.  (For HK pre-opening market and US pre/post-market.True: need. False: not need.)
        session|[Session](../quote/quote.md#8688)|Order session (Only applied to US stocks)
        aux_price|float|Traget price.
        trail_type|[TrailType](./trade.md#12)|Trailing type.
        trail_value|float|Trailing amount/ratio.
        trail_spread|float|Specify spread.
        jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)
        expire_time|str|Order expiration time  (Valid when time_in_force is GTD)
        amount|float|Order amount
        strategy_type|[OptionStrategyType](../quote/quote.md#2931)|Combo strategy type
        combo_legs|list|Combo legs list  (For field details, refer to the ComboLeg table in [place_combo_order](./place-combo-order.md))

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.order_list_query()
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the order list is not empty
        print(data['order_id'][0])  # Get the first order ID of the order list today
        print(data['order_id'].values.tolist())  # Convert to list
else:
    print('order_list_query error: ', data)
trd_ctx.close()
```

* **Output**

```python
        code stock_name order_market    trd_side           order_type   order_status             order_id    qty  price              create_time             updated_time  dealt_qty  dealt_avg_price last_err_msg      remark time_in_force fill_outside_rth session aux_price trail_type trail_value trail_spread currency jp_acc_type
0   US.AAPL                    US         BUY           NORMAL  CANCELLED_ALL  6644468615272262086  100.0  520.0  2021-09-06 10:17:52.465  2021-09-07 16:10:22.806        0.0              0.0               asdfg+=@@@           GTC        N/A      N/A       560        N/A         N/A          N/A      USD        N/A
6644468615272262086
['6644468615272262086']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
* It will be restricted by the frequency limit for this interface only when the cache is refreshed
:::

:::tip Tips
* Open orders are arranged in chronological order: earlier orders return first, followed by later orders.
:::

---

# Get Historical Orders

`history_order_list_query(status_filter_list=[], code='', order_market=TrdMarket.NONE, start='', end='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0)`

* **Description**

    Query the historical order list of a specified trading account

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    status_filter_list|list|Order status filter conditions.  (Only return the data of the specified Order ID. No filtering by default, return all. Data type of elements in the list is [OrderStatus](./trade.md#8074).)
    code|str|Security symbol.  (Only return orders whose related security symbols correspond to these codes. If this parameter is not passed, return all.)
    order_market|[TrdMarket](./trade.md#6257)|Filter orders by security market. (- Return historical orders for the specified market.
  - If this parameter is not passed or the default NONE is used, return historical orders for all markets.)
    start|str|Start time.  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    end|str|End time  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment.  
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)

    * The combination of ***start*** and ***end*** is as follows
        Start type|End type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 90 days before ***end***.
        str|None|***end*** is 90 days after ***start***.
        None|None|***start*** is 90 days before, ***end*** is the current date.

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        order_type|[OrderType](./trade.md#245)|Order type.
        order_status|[OrderStatus](./trade.md#8074)|Order status.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        order_market|[TrdMarket](./trade.md#6257)|Order market.
        qty|float|Order quantity.  (Option futures unit is "Contract".)
        price|float|Order price.  (3 decimal place accuracy, excess part will be rounded.)
        currency|[Currency](./trade.md#1655)|Transaction currency.
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        updated_time|str|Last update time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).The unit of option futures is "Contract".) 
        dealt_qty|float|Deal quantity  (Option futures unit is "Contract".)
        dealt_avg_price|float|Average deal price.  (No precision limit.)
        last_err_msg|str|The last error description.  (If there is an error, the cause of the last error will be returned. If there is no error, an empty string will be returned.)
        remark|str|Identification of remarks when placing an order.  (Refer to remark in the [place_order](./place-order.md) interface parameters for details.)
        time_in_force|[TimeInForce](./trade.md#7678)|Valid period.
        fill_outside_rth|bool|Whether pre-market and after-hours are needed.  (For HK pre-opening market and US pre/post-market.True: need. False: not need.)
        session|[Session](../quote/quote.md#8688)|Order session (Only applied to US stocks)
        aux_price|float|Traget price.
        trail_type|[TrailType](./trade.md#12)|Trailing type.
        trail_value|float|Trailing amount/ratio.
        trail_spread|float|Specify spread.
        jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)
        expire_time|str|Order expiration time  (Valid when time_in_force is GTD)
        amount|float|Order amount
        strategy_type|[OptionStrategyType](../quote/quote.md#2931)|Combo strategy type
        combo_legs|list|Combo legs list  (For field details, refer to the ComboLeg table in [place_combo_order](./place-combo-order.md))
        
* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.history_order_list_query()
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the order list is not empty
        print(data['order_id'][0])  # Get Order ID of the first holding position
        print(data['order_id'].values.tolist())  # Convert to list
else:
    print('history_order_list_query error: ', data)
trd_ctx.close()
```

* **Output**

```python
        code stock_name  order_market  trd_side           order_type   order_status             order_id    qty  price              create_time             updated_time  dealt_qty  dealt_avg_price last_err_msg      remark time_in_force fill_outside_rth session aux_price trail_type trail_value trail_spread currency jp_acc_type
0   US.AAPL                  US          BUY           NORMAL  CANCELLED_ALL  6644468615272262086  100.0  520.0  2021-09-06 10:17:52.465  2021-09-07 16:10:22.806        0.0              0.0               asdfg+=@@@           GTC              N/A       N/A      560        N/A         N/A          N/A      USD        N/A
6644468615272262086
['6644468615272262086']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
:::

:::tip Tips
* Historical orders are arranged in reverse chronological order: later orders return first, followed by earlier orders.
:::

---

# Orders Push Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    In response to orders push, asynchronously process the order status information pushed by OpenD.
    After receiving the order status information pushed by OpenD, this function is called.. You need to override on_recv_rsp in the derived class.

* **Parameters**
    
    Parameter|Type|Description
    :-|:-|:-
    rsp_pb|Trd_UpdateOrder_pb2.Response|This parameter does not need to be processed in the derived class.

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        order_type|[OrderType](./trade.md#245)|Order type.
        order_status|[OrderStatus](./trade.md#8074)|Order status.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        qty|float|Order quantity.  (Option futures unit is "Contract")
        price|float|Order price.  (3 decimal place accuracy, excess part will be rounded.)
        currency|[Currency](./trade.md#1655)|Transaction currency.
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        updated_time|str|Last update time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).The unit of option futures is "Contract".) 
        dealt_qty|float|Deal quantity  (Option futures unit is "Contract")
        dealt_avg_price|float|Average deal price.  (No precision limit.)
        last_err_msg|str|The last error description.  (If there is an error, the cause of the last error will be returned. If there is no error, an empty string will be returned.)
        remark|str|Identification of remarks when placing an order.  (Refer to remark in the [place_order](./place-order.md) interface parameters for details.)
        time_in_force|[TimeInForce](./trade.md#7678)|Valid period.
        fill_outside_rth|bool|Whether pre-market and after-hours are needed.  (Only for US stocks.True: need. False: not need.)
        session|[Session](../quote/quote.md#8688)|Order session (Only applied to US stocks)
        aux_price|float|Traget price.
        trail_type|[TrailType](./trade.md#12)|Trailing type.
        trail_value|float|Trailing amount/ratio.
        trail_spread|float|Specify spread.
        expire_time|str|Order expiration time  (Valid when time_in_force is GTD)
        amount|float|Order amount
        strategy_type|[OptionStrategyType](../quote/quote.md#2931)|Combo strategy type
        combo_legs|list|Combo legs list  (For field details, refer to the ComboLeg table in [place_combo_order](./place-combo-order.md))

* **Example**

```python
from moomoo import *
from time import sleep
class TradeOrderTest(TradeOrderHandlerBase):
    """ order update push"""
    def on_recv_rsp(self, rsp_pb):
        ret, content = super(TradeOrderTest, self).on_recv_rsp(rsp_pb)
        if ret == RET_OK:
            print("* TradeOrderTest content={}\n".format(content))
        return ret, content

trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
trd_ctx.set_handler(TradeOrderTest())
print(trd_ctx.place_order(price=518.0, qty=100, code="US.AAPL", trd_side=TrdSide.SELL))

sleep(15)
trd_ctx.close()
```

* **Output**

```python
* TradeOrderTest content=  trd_env      code stock_name  dealt_avg_price  dealt_qty    qty           order_id order_type  price order_status          create_time         updated_time trd_side last_err_msg trd_market remark time_in_force fill_outside_rth session  aux_price trail_type trail_value trail_spread currency
0    REAL  US.AAPL        Apple Inc.              0.0        0.0  100.0  72625263708670783     NORMAL  518.0   SUBMITTING  2021-11-04 11:26:27  2021-11-04 11:26:27      BUY                      US                  DAY              N/A       N/A        N/A      N/A      N/A          N/A      USD
```

---

# Get Order Fee

`order_fee_query(order_id_list=[], acc_id=0, acc_index=0, trd_env=TrdEnv.REAL)`

* **介绍**

    Get specified orders' fee details. (Minimum version requirement: 8.2.4218)

* **参数**
    Parameter|Type|Description
    :-|:-|:-
    order_id_list|list|Order id list. (- At most 400 orders for each request.
  - The data type of elements in the list is str.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment. 
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    

* **返回**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, order fee list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Order list format as follows：
        字段|类型|说明
        :-|:-|:-
        order_id|str|Order ID
        fee_amount|float|Total fee of the order.
        fee_details|list|Fee details of the order. (- Format：[('item1', fee amount of item1), ('item2', fee amount of item2), ('item3', fee amount of item3)]
  - Common fee items: Commission, Platform Fee, ORF, OCC Fee,Option Settlement Fees, Settlement Fee, SEC Fee, TAF.)
         (Format：[('item1', fee amount of item1), ('item2', fee amount of item2), ('item3', fee amount of item3)])
        
* **Example**
```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret1, data1 = trd_ctx.history_order_list_query(status_filter_list=[OrderStatus.FILLED_ALL])
if ret1 == RET_OK:
    if data1.shape[0] > 0:  # If the order list is not empty
        ret2, data2 = trd_ctx.order_fee_query(data1['order_id'].values.tolist())  # Convert order ids to list data type, and request for order fees.
        if ret2 == RET_OK:
            print(data2)
            print(data2['fee_details'][0])  # Get fee details of the first order
        else:
            print('order_fee_query error: ', data2)
else:
    print('order_list_query error: ', data1)
trd_ctx.close()
```

* **Output**

```python
                                            order_id  fee_amount                                        fee_details
0  v3_20240314_12345678_MTc4NzA5NzY5OTA3ODAzMzMwN       10.46  [(Commission, 5.85), (Platform Fee, 2.7), (ORF...
1  v3_20240318_12345678_MTM5Nzc5MDYxNDY1NDM1MDI1M        2.25  [(Commission, 0.99), (Platform Fee, 1.0), (Set...
[('Commission', 5.85), ('Platform Fee', 2.7), ('ORF', 0.11), ('OCC Fee', 0.18), ('Option Settlement Fees', 1.62)]
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
* Only orders after 2018-01-01 are supported.
* Can not query order fee through paper trading accounts.
* Can not query order fee through Moomoo CA accounts. 

:::

---

# Subscribe to Transaction Push

Python does not need to subscribe to transaction push

---

# Get Today's Deals

`deal_list_query(code="", deal_market= TrdMarket.NONE, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0, refresh_cache=False)`

* **Description**
    
    Query today's deal list of a specific trading account.  
    This feature is only available for live trading and not for paper trading.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    code|str|Security symbol.  (Only return orders whose related security symbols correspond to these codes. If this parameter is not passed, return all.)
    deal_market|[TrdMarket](./trade.md#6257)|Filter deals by security market.  (- Return today's deals for the specified market.
  - If this parameter is not passed or the default NONE is used, return today's deals for all markets.)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment. 
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    refresh_cache|bool|Whether to refresh the cache.  (- True: Re-request data from the moomoo server immediately, without using the OpenD cache. At this time, it will be restricted by the interface frequency limit.
  - False: Use OpenD's cache (the cache needs to be refreshed if it is not updated in rare circumstances).)
    


* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, transaction list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Transaction list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        deal_id|str|Deal number.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        deal_market|[TrdMarket](./trade.md#6257)|Deal market.
        qty|float|Quantity of shares bought/sold on this fill.  (Option futures unit is "Contract".)
        price|float|Fill price.  (3 decimal place accuracy, excess part will be rounded.)
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        counter_broker_id|int|Counter broker ID.  (Only valid for HK stocks.)
        counter_broker_name|str|Counter broker name.  (Only valid for HK stocks.)
        status|[DealStatus](./trade.md#4379)|Deal status.
        jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)
        
* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.deal_list_query()
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the order fill list is not empty
        print(data['order_id'][0])  # Get the first order ID of the transaction list
        print(data['order_id'].values.tolist())  # Convert to list
else:
    print('deal_list_query error: ', data)
trd_ctx.close()
```

* **Output**

```python
    code stock_name                            deal_market     deal_id             order_id    qty  price trd_side              create_time  counter_broker_id counter_broker_name status jp_acc_type
0  US.AAPL       Apple Inc.                      HK  5056208452274069375  4665291631090960915  100.0  370.0      BUY  2020-09-17 21:15:59.979                  5                         OK        N/A
4665291631090960915
['4665291631090960915']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
* It will be restricted by the frequency limit for this interface only when refresh_cache is True
:::

:::tip Tips
* Today's deals are arranged in chronological order: earlier deals return first, followed by later deals.
:::

---

# Get Historical Deals

`history_deal_list_query(code='', deal_market=TrdMarket.NONE, start='', end='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0)`

* **Description**

    Query historical deal list of a specific trading account.  
    This feature is only available for live trading and not for paper trading.

* **Parameters**

    Parameter|Type|Description
    :-|:-|:-
    code|str|Security symbol.  (Only return orders whose related security symbols correspond to these codes. If this parameter is not passed, return all.)
    deal_market|[TrdMarket](./trade.md#6257)|Filter deals by security market.  (- Return historical deals for the specified market.
  - If this parameter is not passed or the default NONE is used, return historical deals for all markets.)
    start|str|Start time.  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    end|str|End time.  (In strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
    trd_env|[TrdEnv](./trade.md#48)|Trading environment. 
    acc_id|int|Trading account ID.  (- When acc_id is 0, the account specified by acc_index is chosen.
  -  When acc_id is set the ID number (not 0), the account specified by acc_id is chosen.
  - Using acc_id to query and trade is strongly recommended, acc_index will change when adding/closing an account, result in the account you specify is inconsistent with the actual trading account.)
    acc_index|int|The account number in the trading account list.  (The default is 0, which means the first trading account.)
    
    * The combination of ***start*** and ***end*** is as follows
        Start type|End type|Description
        :-|:-|:-
        str|str|***start*** and ***end*** are the specified dates respectively.
        None|str|***start*** is 90 days before ***end***.
        str|None|***end*** is 90 days after ***start***.
        None|None|***start*** is 90 days before, ***end*** is the current date.

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, transaction list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Transaction list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        deal_id|str|Deal number.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        deal_market|[TrdMarket](./trade.md#6257)|Deal market.
        qty|float|Quantity of shares bought/sold on this fill.  (Option futures unit is "Contract".)
        price|float|Fill price.  (3 decimal place accuracy, excess part will be rounded.)
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        counter_broker_id|int|Counter broker ID.  (Only valid for HK stocks.)
        counter_broker_name|str|Counter broker name.  (Only valid for HK stocks.)
        status|[DealStatus](./trade.md#4379)|Deal status.
        jp_acc_type|[SubAccType](./trade.md#3947)|JP sub account type  (Only applicable for Moomoo JP)

* **Example**

```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
ret, data = trd_ctx.history_deal_list_query()
if ret == RET_OK:
    print(data)
    if data.shape[0] > 0:  # If the order fill list is not empty
        print(data['deal_id'][0])  # Get the first deal ID of the history order fill list
        print(data['deal_id'].values.tolist())  # Convert to list
else:
    print('history_deal_list_query error: ', data)
trd_ctx.close()  # Close the current connection
```

* **Output**

```python
    code     stock_name      deal_market      deal_id             order_id      qty    price  trd_side     create_time          counter_broker_id counter_broker_name status jp_acc_type
0  US.AAPL   Apple Inc.           US  5056208452274069375  4665291631090960915  100.0  370.0    BUY    2020-09-17 21:15:59.979          5                                 OK        N/A
5056208452274069375
['5056208452274069375']
```

:::tip Interface Limitations
* A maximum of 10 requests per 30 seconds under a single account ID (acc_id).
:::

:::tip Tips
* Historical deals are arranged in reverse chronological order: later deals return first, followed by earlier deals.
:::

---

# Deals Push Callback

`on_recv_rsp(self, rsp_pb)`

* **Description**

    In response to the transaction push, asynchronously process the transaction status information pushed by OpenD.
    After receiving the order fill information pushed by OpenD, this function is called. You need to override on_recv_rsp in the derived class.  
    This feature is only available for live trading and not for paper trading.
 
* **Parameters**
    
    Parameter|Type|Description    
    :-|:-|:-
    rsp_pb|Trd_UpdateOrderFill_pb2.Response|This parameter does not need to be processed in the derived class.

* **Return**
    
    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td><a href="../ftapi/common.html#8800"> RET_CODE</a></td>
            <td>Interface result.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>pd.DataFrame</td>
            <td>If ret == RET_OK, transaction list is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * Transaction list format as follows: 
        Field|Type|Description
        :-|:-|:-
        trd_side|[TrdSide](./trade.md#832)|Trading direction.
        deal_id|str|Deal number.
        order_id|str|Order ID.
        code|str|Security code.
        stock_name|str|Security name.
        qty|float|Quantity of shares bought/sold on this fill.  (Option futures unit is "Contract".)
        price|float|Fill price. 
        create_time|str|Create time.  (For time zone of futures, please refer to [OpenD Configuration](../opend/opend-cmd.md#149).)
        counter_broker_id|int|Counter broker ID.  (Only valid for HK stocks.)
        counter_broker_name|str|Counter broker name.  (Only valid for HK stocks.)
        status|[DealStatus](./trade.md#4379)|Deal status.

* **Example**

```python
from moomoo import *
from time import sleep
class TradeDealTest(TradeDealHandlerBase):
    """ order update push"""
    def on_recv_rsp(self, rsp_pb):
        ret, content = super(TradeDealTest, self).on_recv_rsp(rsp_pb)
        if ret == RET_OK:
            print("TradeDealTest content={}".format(content))
        return ret, content

trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUINC)
trd_ctx.set_handler(TradeDealTest())
print(trd_ctx.place_order(price=595.0, qty=100, code="US.AAPL", trd_side=TrdSide.BUY))

sleep(15)
trd_ctx.close()
```

* **Output**

```python
TradeDealTest content=  trd_env      code stock_name              deal_id             order_id    qty  price trd_side              create_time  counter_broker_id counter_broker_name trd_market status
0    REAL  US.AAPL      Apple Inc.  2511067564122483295  8561504228375901919  100.0  518.0      BUY  2021-11-04 11:29:41.595                  5                   5         US     OK
```

---

# Trading Definitions

## Account Risk Control Level

> **CltRiskLevel**

* `NONE`

  Unknown

* `SAFE`

  Safe

* `WARNING`

  Warning

* `DANGER`

  Danger

* `ABSOLUTE_SAFE`

  Absolutely safe

* `OPT_DANGER`

  Danger  (Option related.)

:::tip Tips
* It is recommanded to use risk_status field to get risk status of futures account, see [CltRiskStatus](./trade.md#7469)
:::

## Currency Type

> **Currency**

* `NONE`

  Unknown currency

* `HKD`

  HK dollar

* `USD`

  US dollar

* `CNH`

  Offshore RMB

* `JPY`

  Japanese Yen

* `SGD`

  SG dollar

* `AUD`

  Australian dollar

* `CAD`

  Canadian dollar

* `MYR`

  Malaysian Ringgit

## TrailType

**TrailType**

* `NONE`

  Unknown

* `RATIO`

  Trailing ratio

* `AMOUNT`

  Trailing amount

## Modify Order Operation

> **ModifyOrderOp**

* `NONE`

  Unknown operation

* `NORMAL`

  Modify order

* `CANCEL`

  Cancel  (The uncompleted order will be directly cancelled from the exchange matching queue.)

* `DISABLE`

  Disable  (- To the exchange, DISABLE is the same as CANCEL.
  - After the order is invalid, the unfilled order will be directly withdrawn from the exchange matching queue, but the order information (such as price and quantity) will continue to be retained in Futu server, and you still can ENABLE it.)

* `ENABLE`

  Enable  (- Validate the invalid order. To the exchange, ENABLE is the same as placing a new order. 
  - After the order is validated, the order will be re-submitted to the exchange according to the original price and quantity, and the re-validated orders need to be re-queued in the order of price priority and time priority.)

* `DELETE`

  Delete  (Hide the order that is canceled or failed.)

## Transaction Status

> **DealStatus**

* `OK`

  Transaction success

* `CANCELLED`

  Transaction cancelled

* `CHANGED`

  Transaction changed

## Order Status

> **OrderStatus**

* `NONE`

  Unknown status

* `WAITING_SUBMIT`

  Queued  (Futu server has received your order and is preparing to submit it to the exchange.)

* `SUBMITTING`

  Submitting  (Futu server has sent your order to the exchange, and the exchange is processing the order.)

* `SUBMITTED`

  Working  (Order has been successfully submitted to the exchange.)

* `FILLED_PART`

  Partially filled  (You can choose to cancel, or wait for fullly filled.)

* `FILLED_ALL`

  Fully filled

* `CANCELLED_PART`

  Partially cancelled

* `CANCELLED_ALL`

  Fully cancelled

* `FAILED`

  Failed. Rejected by server.

* `DISABLED`

  Deactivated  (Actively operate a disabled order, this will not be submitted to the exchange.)

* `DELETED`

  Deleted, only unfilled orders can be deleted  (The status after you actively delete the order.)

## Order Type

:::tip Tips
* [Order types supported in live trading](../qa/trade.md#7467).
* Paper trade only supports limit orders (NORMAL) and market orders (MARKET).
:::

> **OrderType**

* `NONE`

  Unknown type.

* `NORMAL`

  Limit orders.

* `MARKET`

  Market orders.

* `ABSOLUTE_LIMIT`

  Absolute limit orders.  (Only the price exactly matches before the transaction, otherwise the order will fail.
  -  Example: For the next absolute limit buy order with a price of 5 dollers, the seller's price must also be 5 dollers to complete the transaction. The seller cannot complete the transaction even if it is less than 5 yuan, and the order fails. The same goes for selling.)

* `AUCTION`

  At-auction market orders.  (Valid for HK stocks early and closing auctions only)

* `AUCTION_LIMIT`

  At-auction limit orders.  (Valid for HK stocks early and closing auctions only. Participate in the auction, and the specified price is required to be traded.)

* `SPECIAL_LIMIT`

  Special limit orders.  (The transaction rules are the same as enhanced limit orders, and the exchange will automatically cancel the order after partial transaction.)

* `SPECIAL_LIMIT_ALL`

  AON special limit orders.  (The order must be fully filled, otherwise cancelled automatically.)

* `STOP`

  Stop orders.

* `STOP_LIMIT`

  Stop Limit orders. 

* `MARKET_IF_TOUCHED`

  Market if Touched orders.

* `LIMIT_IF_TOUCHED`

  Limit if Touched orders. 

* `TRAILING_STOP`

  Trailing Stop orders.

* `TRAILING_STOP_LIMIT`

  Trailing Stop Limit orders.

* `TWAP_LIMIT `

  Time Weighted Average Price Limit orders (HK and US securities only).  (Algo orders only support order queries and do not support trading.)

* `TWAP`

  Time Weighted Average Price Market orders (US securities only).  (Algo orders only support order queries and do not support trading.)

* `VWAP_LIMIT `

  Volume Weighted Average Price Limit orders (HK and US securities only).  (Algo orders only support order queries and do not support trading.)

* `VWAP `

  Volume Weighted Average Price Market orders (US securities only).  (Algo orders only support order queries and do not support trading.)

## Position Direction

> **PositionSide**

* `NONE`

  Unknown position

* `LONG`

  Long position, by default

* `SHORT`

  Short position

## Option Combo Position Type

> **PositionType**

* `NONE`

  Unknown

* `COMBINED`

  Combined summary position

* `LEG`

  Single-leg position

## Account Type

> **TrdAccType**

* `NONE`

  Unknown type

* `CASH`

  Cash account

* `MARGIN`

  Margin account

* `TFSA`

  Canadian TFSA account
  
* `RRSP`

  Canadian RRSP account

* `SRRSP`

  Canadian SRRSP account

* `DERIVATIVE`

  Japanese derivative account

## Trading Environment

> **TrdEnv**

* `SIMULATE`

  Simulated environment

* `REAL`

  Real environment

## Transaction Market

> **TrdMarket**

* `NONE`

  Unknown market

* `HK`

  Hong Kong market

* `US`

  US market

* `CN`

  A-share market  (The A-share market only supports paper trading, not live trading.)

* `HKCC`

  HKCC market  (- The HKCC market only supports live trading, not paper trading.
  - The HKCC market can only trade Shanghai Stock Connect and Shenzhen Stock Connect stocks. For details, please refer to HKEX [HKCC List](https://www.hkex.com.hk/mutual-market/stock-connect/eligible-stocks/%20view-all-eligible-securities?sc_lang=zh-HK).)

* `FUTURES`

  Futures market

* `FUTURES_SIMULATE_US` 

  US futures simulated market  (Minimum OpenD version requirements: 7.7.3908)

* `FUTURES_SIMULATE_HK`

  Hong Kong futures simulated market  (Minimum OpenD version requirements: 7.7.3908)

* `FUTURES_SIMULATE_SG`

  Singapore futures simulated market  (Minimum OpenD version requirements: 7.7.3908)

* `FUTURES_SIMULATE_JP`

  Japan futures simulated market  (Minimum OpenD version requirements: 7.7.3908)

* `HKFUND`

  HK fund market  (Minimum OpenD version requirements: 8.2.4218)

* `USFUND`

  US fund market  (Minimum OpenD version requirements: 8.2.4218)

* `SG`

  SG market  (Minimum OpenD version requirements: 9.0.5008)

* `JP`

  JP market  (Minimum OpenD version requirements: 9.0.5008)

* `AU`

  AU market  (Minimum OpenD version requirements: 9.0.5008)

* `MY`

  MY market  (Minimum OpenD version requirements: 9.0.5008)

* `CA`

  CA market  (Minimum OpenD version requirements: 9.0.5008)

## Account Status

> **TrdAccStatus**

* `ACTIVE`

  Active account

* `DISABLED`

  Disabled account


## Account Structure

> **TrdAccRole**

* `NONE`

  Unknown

* `MASTER`

  Master account

* `NORMAL`

  Normal account

* `IPO`

  Malaysian IPO account


## Transaction Securities Market


## Transaction Direction

> **TrdSide**

* `NONE`

  Unknown direction

* `BUY`

  Buy

* `SELL`

  Sell

* `SELL_SHORT`

  Sell short  (- Only applicable for Moomoo JP
  - Other brokers are only used for order list display and are not recommended as a direction for placing orders.)

* `BUY_BACK`

  Buy back  (- Only applicable for Moomoo JP
  - Other brokers are only used for order list display and are not recommended as a direction for placing orders.)

:::tip Tips
It is recommanded that only use `Buy` or `Sell` as the input parameter of direction of **place_order** interface.  
`BuyBack` and `SellShort` is only used as the display field for **Get Order List** , **Get History Order List**, **Orders Push Callback**, **Get Today's Deals**, **Get Historical Deals** and **Deals Push Callback** interface.
:::

## Order Validity Period

> **TimeInForce**

* `DAY`

  Good for the day

* `GTC`

  Good until cancel

* `IOC`

  Immediate or cancel  (Only for crypto market orders)

* `GTD`

  Good Till Date

## Securities Firm to Which the Account Belongs

> **SecurityFirm**

* `NONE`

  Unknown

* `FUTUSECURITIES`

  FUTU HK

* `FUTUINC`
  
  Moomoo US

* `FUTUSG`  

  Moomoo SG

* `FUTUAU`  

  Moomoo AU

* `FUTUCA`  

  Moomoo CA

* `FUTUMY`  

  Moomoo MY

* `FUTUJP`  

  Moomoo JP

## Simulate Account Type

> **SimAccType**

* `NONE`

  Unknown

* `STOCK`

  Stock Paper Trading

* `OPTION`

  Option Paper Trading

* `FUTURES`

  Futures Paper Trading

* `STOCK_AND_OPTION`

  US Margin Account (Paper Trading)

## Account Risk Control Status

> **CltRiskStatus**

* `NONE`

  Unknown

* `LEVEL1`

  Very Safe

* `LEVEL2`

  Safe

* `LEVEL3`

  Safe

* `LEVEL4`

  Low Risk

* `LEVEL5`

  Medium Risk

* `LEVEL6`

  High Risk

* `LEVEL7`

  Warning

* `LEVEL8`

  Margin Call

* `LEVEL9`

  Margin Call

## Exposure Level

> **ExposureLevel**

* `NONE`

  Unknown

* `NORMAL`

  Normal  (Remaining limit/Position limit > 10%, can buy virtual assets normally)

* `NEAR_LIMIT`

  Near Limit  (10% >= Remaining limit/Position limit > 0%, please pay attention to the remaining limit)

* `RESTRICTED`

  Restricted  (Remaining limit/Position limit = 0%, buying virtual assets is prohibited)

* `SAFE`

  Safe  (Equity with loan value >= Initial margin requirement, no risk)

* `MODERATE`

  Moderate  (Remaining liquidity >= 10% * Equity with loan value, low risk with leverage trading)

* `WARNING`

  Warning  (Remaining liquidity < 10% * Equity with loan value, risk may intensify)

* `MARGIN_CALL`

  Margin Call  (Equity with loan value <= Maintenance margin requirement)

## Day-trading Status

> **DtStatus**

* `NONE`

  Unknown

* `Unlimited`

  Unlimited  (You can day trade for unlimited times. But you pay attention to your remaining day-trading buying power.)

* `EM_Call`

  EM-Call  (You cannot initiate any new positions now. You should make your equity over $25000, or you cannot initiate any new positions for 90 days.)

* `DT_Call`

  DT-Call  (You have an unmet day-trading margin call. And you have five business days to deposit funds to meet the DT Call to get more DTBP. If your DT Call past due, you will not be allowed to initiate any new positions for 90 days until the DT call is met.)

## Cash Flow Direction

> **CashFlowDirection**

* `NONE`

  Unknown

* `IN`

  Cash Inflow

* `OUT`

  Cash Outflow


## JP Sub Account Type

> **SubAccType**

* `NONE`

  Unknown

* `JP_GENERAL`

  General - long

* `JP_TOKUTEI`

  Specified - long

* `JP_NISA_GENERAL`

  General NISA

* `JP_NISA_TSUMITATE`

  Tsumitate NISA

* `JP_GENERAL_SHORT`

  General - short

* `JP_TOKUTEI_SHORT`

  Specified - short

* `JP_HONPO_GENERAL`

  Domestic Margin Trading Collateral - General

* `JP_GAIKOKU_GENERAL`

  Foreign Margin Trading Collateral - General

* `JP_HONPO_TOKUTEI`

  Domestic Margin Trading Collateral - Specified

* `JP_GAIKOKU_TOKUTEI`

  Foreign Margin Trading Collateral - Specified

* `JP_DERIVATIVE_LONG`

  Derivatives Sub-account - Long

* `JP_DERIVATIVE_SHORT`

  Derivatives Sub-account - Short

* `JP_HONPO_DERIVATIVE_GENERAL`

  Domestic Derivatives Margin Sub-account - General

* `JP_GAIKOKU_DERIVATIVE_GENERAL`

  Foreign Derivatives Margin Sub-account - General

* `JP_HONPO_DERIVATIVE_TOKUTEI`

  Domestic Derivatives Margin Sub-account - Specific

* `JP_GAIKOKU_DERIVATIVE_TOKUTEI`

  Foreign Derivatives Margin Sub-account - Specific

## Asset Category

> **AssetCategory**

* `NONE`

  Unknown

* `JP`

  Domestic

* `US`

  Foreign

## Transaction Category

**TrdCategory**

```protobuf
enum TrdCategory
{
    TrdCategory_Unknown = 0; //Unknown
    TrdCategory_Security = 1; //Securities
    TrdCategory_Future = 2; //Futures
}
```

## Account Cash Information

**AccCashInfo**

```protobuf
message AccCashInfo
{
    optional int32 currency = 1; //Currency type, refer to Currency
    optional double cash = 2; //Cash balance
    optional double availableBalance = 3; //Available cash withdrawal amount
    optional double netCashPower = 4;		// Net cash power
}
```

## Account Assets Information by Market

**AccMarketInfo**

```protobuf
message AccCashInfo
{
    optional int32 trdMarket = 1;        // Trading market, refer to TrdMarket
    optional double assets = 2;          // Account assets information by market
}
```


## Transaction Protocol Public Header

**TrdHeader**

```protobuf
message TrdHeader
{
  required int32 trdEnv = 1; //Trading environment, refer to the enumeration definition of TrdEnv
  required uint64 accID = 2; //Trading account, trading account should match to trading environment and market permissions, otherwise an error will be returned
  required int32 trdMarket = 3; //Trading market, refer to the enumeration definition of TrdMarket
  optional int32 jpAccType = 4; //JP sub account type，refer to TrdSubAccType
}
```

## Trading Account

**TrdAcc**

```protobuf
message TrdAcc
{
  required int32 trdEnv = 1; //Trading environment, refer to the enumeration definition of TrdEnv
  required uint64 accID = 2; //Trading account
  repeated int32 trdMarketAuthList = 3; //The trading market permissions supported by the trading account, can have multiple trading market permissions, currently only a single, refer to the enumeration definition of TrdMarket
  optional int32 accType = 4; //Account type, refer to TrdAccType
  optional string cardNum = 5; //card number
  optional int32 securityFirm = 6; //security firm，refer to SecurityFirm
  optional int32 simAccType = 7; //simulate account type, see SimAccType
  optional string uniCardNum = 8; //Universal account number
  optional int32 accStatus = 9; //Account status，refer to TrdAccStatus
  optional int32 accRole = 10; //Account Structure, used to distinguish between master and normal account, refer to TrdAccRole
  repeated int32 jpAccType = 11; //JP sub account type, refer to TrdSubAccType
}
```

## Account Funds

**Funds**

```protobuf
message Funds
{
  required double power = 1; //Maximum Buying Power (Minimum OpenD version requirements: 5.0.1310. This field is the approximate value calculated according to the marginable initial margin of 50%. But in fact, this ratio of each financial contract is not the same. We recommend using Buy on Margin, returned by Query the Maximum Quantity that Can be Bought or Sold, to get the maximum quantity can buy.) 
  required double totalAssets = 2; //Net Assets
  required double cash = 3; //Cash (Only Single market accounts use this field. If your account is an universial account, please use cashInfoList to get cash for each currency.)
  required double marketVal = 4; //Securities Market Value (only applicable to securities accounts)
  required double frozenCash = 5; //Funds on Hold 
  required double debtCash = 6; //Interest Charged Amount (Minimum OpenD version requirements: 5.0.1310) 
  required double avlWithdrawalCash = 7; //Withdrawable Cash (Only Single market accounts use this field. If your account is an universial account, please use cashInfoList to get withdrawalbe cash for each currency.)

  optional int32 currency = 8;            //The currency used for this query (only applicable to universal securities accounts and futures accounts). See Currency
  optional double availableFunds = 9;     //Available funds (only applicable to futures accounts)
  optional double unrealizedPL = 10;      //Unrealized gain or loss (only applicable to futures accounts)
  optional double realizedPL = 11;        //Realized gain or loss (only applicable to futures accounts)
  optional int32 riskLevel = 12;           //Risk control level (only applicable to futures accounts), See CltRiskLevel. It is recommanded to use riskStatus field to get the risk status of securities accounts or futures accounts.
  optional double initialMargin = 13;      //Initial Margin (only applicable to futures accounts, minimum OpenD version requirements: 5.0.1310)
  optional double maintenanceMargin = 14;  //Maintenance Margin (Minimum OpenD version requirements: 5.0.1310) 
  repeated AccCashInfo cashInfoList = 15;  //Cash information by currency (only applicable to futures accounts)
  optional double maxPowerShort = 16; //Short Buying Power (Minimum OpenD version requirements: 5.0.1310. This field is the approximate value calculated according to the shortable initial margin of 60%. But in fact, this ratio of each financial contract is not the same. We recommend using the Short sell field, returned by the API of Query the Maximum Quantity that Can be Bought or Sold, to get the maximum quantity can be shorted.) 
  optional double netCashPower = 17;  //Cash Buying Power （Only Single market accounts use this field. If your account is an universial account, please use cashInfoList to get cash buying power for each currency.）
  optional double longMv = 18;        //Long Market Value (Minimum OpenD version requirements: 5.0.1310) 
  optional double shortMv = 19;       //Short Market Value (Minimum OpenD version requirements: 5.0.1310) 
  optional double pendingAsset = 20;  //Asset in Transit (Minimum OpenD version requirements: 5.0.1310) 
  optional double maxWithdrawal = 21;          //Maximum Withdrawal (only applicable to securities accounts, minimum OpenD version requirements: 5.0.1310) 
  optional int32 riskStatus = 22;              //Risk status (only applicable to securities accounts, minimum OpenD version requirements: 5.0.1310), divided into 9 grades, LEVEL1 is the safest and LEVEL9 is the most dangerous. See CltRiskStatus
  optional double marginCallMargin = 23;       //Margin-call Margin (Minimum OpenD version requirements: 5.0.1310) 
  
  optional bool isPdt = 24;				//Is it marked as a PDT. True: It is a PDT.  False: Not a PDT. Only applicable to securities accounts of moomoo US. Minimum OpenD version requirements: 5.8.2008.
  optional string pdtSeq = 25;			//Day Trades Left. Only applicable to securities accounts of moomoo US. Minimum OpenD version requirements: 5.8.2008. 
  optional double beginningDTBP = 26;		//Beginning DTBP. Only applicable to securities accounts of moomoo US marked as a PDT. Minimum OpenD version requirements: 5.8.2008.
  optional double remainingDTBP = 27;		//Remaining DTBP. Only applicable to securities accounts of moomoo US marked as a PDT. Minimum OpenD version requirements: 5.8.2008.
  optional double dtCallAmount = 28;		//Day-trading Call Amount. Only applicable to securities accounts of moomoo US marked as a PDT. Minimum OpenD version requirements: 5.8.2008.
  optional int32 dtStatus = 29;				//Day-trading Status. Only applicable to securities accounts of moomoo US marked as a PDT. Minimum OpenD version requirements: 5.8.2008.
  
  optional double securitiesAssets = 30; // Net asset value of securities
  optional double fundAssets = 31; // Net asset value of fund
  optional double bondAssets = 32; // Net asset value of bond

repeated AccMarketInfo marketInfoList = 33; //Account assets information by market
}
```

## Account Holding

**Position**

```protobuf
message Position
{
    required uint64 positionID = 1; //Position ID, a unique identifier of a position
    required int32 positionSide = 2; //Position direction, refer to the enumeration definition of PositionSide
    required string code = 3; //Code
    required string name = 4; //Name
    required double qty = 5; //Holding quantity, 2 decimal places, the same below
    required double canSellQty = 6; //Available quantity. Available quantity = Holding quantity - Frozen quantity. The unit of options and futures is "contract".
    required double price = 7; //Market price, 3 decimal places, 2 decimal places for futures
    optional double costPrice = 8; //Diluted Cost (for securities account). Average opening price (for futures account). No precision limit for securities. 2 decimal places for futures. If not passed, it means this value is invalid at this time.
    required double val = 9; //Market value, 3 decimal places, value of this field for futures is 0
    required double plVal = 10; //Amount of profit or loss, 3 decimal places,  2 decimal places for futures
    optional double plRatio = 11; //Percentage of profit or loss(under diluted cost price mode), no precision limit, if not passed, it means this value is invalid at this time
    optional int32 secMarket = 12; //The market to which the securities belong, refer to enumeration definition of TrdSecMarket
    
    //The following is the statistics of this position today
    optional double td_plVal = 21; //Today's profit or loss, 3 decimal places, the same below,  2 decimal places for futures
    optional double td_trdVal = 22; //Today's trading volume, not applicable for futures
    optional double td_buyVal = 23; //Total value bought today, not applicable for futures
    optional double td_buyQty = 24; //Total amount bought today, not applicable for futures
    optional double td_sellVal = 25; //Total value sold today, not applicable for futures
    optional double td_sellQty = 26; //Total amount sold today, not applicable for futures

    optional double unrealizedPL = 28; //Unrealized profit or loss (only applicable to futures accounts)
    optional double realizedPL = 29; //Realized profit or loss (only applicable to futures accounts)
    optional int32 currency = 30;        // Currency type, refer to Currency
    optional int32 trdMarket = 31;  //Trading market, refer to the enumeration definition of TrdMarket

    optional double dilutedCostPrice = 32;  //diluted cost price，applicable for securities accounts only
    optional double averageCostPrice = 33;  //average cost price，not applicable for securities papper trading accounts
    optional double averagePlRatio = 34;  //Percentage of profit or loss(under average cost price mode), no precision limit, if not passed, it means this value is invalid at this time

    optional uint64 comboID = 35;       //Option combo ID
    optional int32 strategyType = 36;   //Option strategy type, refer to Qot_Common.OptionStrategyType
    optional int32 positionType = 37;   //Option combo position type, refer to PositionType
    optional uint64 accID = 38;         //Trading account ID
    optional int32 jpAccType = 39;      //JP sub account type, refer to TrdSubAccType
}
```

## Order

**Order**

```protobuf
message Order
{
    required int32 trdSide = 1; //Trading direction, refer to TrdSide enumeration definition
    required int32 orderType = 2; //Order type, refer to enumeration definition of OrderType
    required int32 orderStatus = 3; //Order status, refer to enumeration definition of OrderStatus
    required uint64 orderID = 4; //Order number
    required string orderIDEx = 5; //Extended order number (only for checking the problem)
    required string code = 6; //code
    required string name = 7; //Name
    required double qty = 8; //Order quantity,  3 decimal places, option unit is "Zhang"
    optional double price = 9; //Order price, 3 decimal places
    required string createTime = 10; //Create time, strictly in accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format
    required string updateTime = 11; //The last update time, strictly according to YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format
    optional double fillQty = 12; //Filled quantity, 2 decimal place accuracy, the option unit is "contract"
    optional double fillAvgPrice = 13; //Average price of the fill, no precision limit
    optional string lastErrMsg = 14; //The last error description, if there is an error, there will be this description of the reason for the last error, no error is empty
    optional int32 secMarket = 15; //The market to which the securities belong, refer to enumeration definition of TrdSecMarket
    optional double createTimestamp = 16; //Timestamp for creation
    optional double updateTimestamp = 17; //Timestamp for last update
    optional string remark = 18; //User remark string, the maximum length is 64 bytes
    optional double auxPrice = 21; //Trigger price
    optional int32 trailType = 22; //Trailing type, see Trd_Common.TrailType enumeration definition
    optional double trailValue = 23; //Trailing amount / ratio
    optional double trailSpread = 24; //Specify spread
    optional int32 currency = 25;        // Currency type, refer to Currency
    optional int32 trdMarket = 26;  //Trading market, refer to the enumeration definition of TrdMarket
    optional int32 session = 27; //Trading session, refer to the enumeration definition of Session
    optional int32 jpAccType = 28; //JP sub account type，refer to TrdSubAccType
    optional string expireTime = 29;  //When timeInForce is GTD, this indicates the order expiration time
    optional double orderAmount = 30;  // Order amount
    optional int32 strategyType = 31;  // Option strategy type, refer to Qot_Common.OptionStrategyType
    repeated Qot_Common.ComboLeg comboLegs = 32; //Leg data for combo option order
}
```

## Order Fee Item

**OrderFeeItem**

```protobuf
message OrderFeeItem
{
    optional string title = 1; //Fee title
    optional double value = 2; //Fee Value
}
```

## Order Fee

**OrderFee**

```protobuf
message OrderFee
{
    required string orderIDEx = 1; //Server order id
    optional double feeAmount = 2; //Fee amount
    repeated OrderFeeItem feeList = 3; //Fee details
}
```

## Order Fill

**OrderFill**

```protobuf
message OrderFill
{
    required int32 trdSide = 1; //Trading direction, refer to enumeration definition of TrdSide
    required uint64 fillID = 2; //OrderFill ID
    required string fillIDEx = 3; //Extended OrderFill ID (only for checking the problem)
    optional uint64 orderID = 4; //Order ID
    optional string orderIDEx = 5; //Extended order ID (only when checking the problem)
    required string code = 6; //code
    required string name = 7; //Name
    required double qty = 8; //Filled quantity, 2 decimal place accuracy, the option unit is "contract"
    required double price = 9; //Price of the fill, 3 decimal places
    required string createTime = 10; //Create time (transaction time), in strict accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format
    optional int32 counterBrokerID = 11; //Counter Broker ID, valid for Hong Kong stocks
    optional string counterBrokerName = 12; //Counter Broker Name, valid for Hong Kong stocks
    optional int32 secMarket = 13; //Securities belong to the market, refer to enumeration definition of TrdSecMarket
    optional double createTimestamp = 14; //Create a timestamp
    optional double updateTimestamp = 15; //last update timestamp
    optional int32 status = 16; //Deal status, refer to enumeration definition of OrderFillStatus
    optional int32 trdMarket = 17;  //Trading market, refer to enumeration definition of TrdMarket
    optional int32 jpAccType = 18; //JP sub account type，refer to TrdSubAccType
}
```

## Maximum Trading Quantity

**MaxTrdQtys**

```protobuf
message MaxTrdQtys
{
    //Due to the current server's implementation, it is required to sell the holding positions before a short selling, and to buy back short positions before a long buying (two steps). Nevertheless a bulish buying can be bought in one step with cash and financing. Please note this difference
    required double maxCashBuy = 1; //Buy on cash. (Maximum quantity that can be bought in cash. The unit of options is "contract".Futures accounts are not applicable.)
    optional double maxCashAndMarginBuy = 2; //Buy on margin. (Maximum quantity that can be bought on margin. The unit of options is "contract". Futures accounts are not applicable.)
    required double maxPositionSell = 3; //Sell on position. (Maximum quantity can be sold. The unit of options is "contract".)
    optional double maxSellShort = 4; //Short sell. (Maximum quantity can be shorted. The unit of options is "contract". Futures accounts are not applicable.)
    optional double maxBuyBack = 5; //Short positions. (Buyback required quantity to close a position. When holding short positions, you must first buy back the short positions before you can continue to buy long. The unit of options and futures is "contract".)
    optional double longRequiredIM = 6;         //Initial margin change when buying one contract of an asset. Only futures and options apply. No position: Returns the initial margin needed to buy one contract (a positive value).   Long position: Returns the initial margin required to buy one contract (a positive value). Short position: Returns the initial margin released for buying back one contract (a negative value). 
    optional double shortRequiredIM = 7;        //Initial margin change when selling one contract of an asset. Currently only futures and options apply. No position: Returns the initial margin needed to short one contract (a positive value). Long position: Returns the initial margin released for selling one contract (a negative value).  Short position: Returns the initial margin needed to short one contract (a positive value).
}
```

## Combo Tradable Info

**ComboMaxTrdQtys**

```protobuf
message ComboMaxTrdQtys
{
    optional double nlvChange = 1;    //Net liquidation value change
    optional double initialMarginChange = 2;    //Initial margin change
    optional double maintenanceMarginChange = 3;    //Maintenance margin change
    optional double optionBuyPower = 4;    //Option buying power
    optional double maxWithDrawChange = 5;    //Maximum withdrawable change
    optional double buyPowerDecrease = 6;    //Buying power decrease
}
```

## Combo Leg

**ComboLeg**

```protobuf
message ComboLeg
{
	required Qot_Common.Security security = 1; //Stock/option
    optional int32 side = 2; //Direction, see Trd_Common.TrdSide
    optional double qtyRatio = 3; //Quantity ratio
    optional uint64 positionID = 4; //Position ID, for moomoo JP close only
}
```

## Cash Flow Summary Info

**FlowSummaryInfo**

```protobuf
message FlowSummaryInfo
{
	optional string clearingDate = 1; //clearing date
	optional string settlementDate = 2; //settlement date
	optional int32 currency = 3; //currency
	optional string cashFlowType = 4; //cash flow type
	optional int32 cashFlowDirection = 5; //cash flow direction, refer to TrdCashFlowDirection
	optional double cashFlowAmount = 6; //amount
	optional string cashFlowRemark = 7; //remark
	optional uint64 cashFlowID = 8; //cash flow ID
}
```

## Filter Conditions

**TrdFilterConditions**

```protobuf
message TrdFilterConditions
{
  repeated string codeList = 1; //Code filtering, only returns the products for these codes, and this condition is ignored if it is not set
  repeated uint64 idList = 2; //ID primary key filter, only returns the products with these IDs, no filtering is not passed, orderID for order, fillID for deal, positionID for position
  optional string beginTime = 3; //Start time, strictly in accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. It is invalid for holding positions, and historical data must be filled in
  optional string endTime = 4; //The end time, strictly in accordance with YYYY-MM-DD HH:MM:SS or YYYY-MM-DD HH:MM:SS.MS format. It is invalid for holding positions, and historical data must be filled in
  repeated string orderIDExList = 5; // The server order id list, which can be used instead of orderID list, or choose one from orderID list
  optional int32 filterMarket = 6; //Trading market filter, refer to enumeration definition of TrdMarket
}
```

---

# Basic Functions


## Set Interface Information(deprecated)

`set_client_info(client_id, client_ver)`

* **Introduction**

    Set calling interface information (unnecessary).

* **Parameters**
    - client_id: the identification of the client
    - client_ver: the version number of the client

```python
from moomoo import *
SysConfig.set_client_info("MymoomooAPI", 0)
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close()
```

## Set Protocol Format

`set_proto_fmt(proto_fmt)`

* **Introduction**

    Set the communication protocol body format, Protobuf and Json formats are currently supported , default ProtoBuf, unnecessary interface

* **Parameters**
    - proto_fmt: protocol format, refer to [ProtoFMT](./common.md#4358)

* **Example**

```python
from moomoo import *
SysConfig.set_proto_fmt(ProtoFMT.Protobuf)
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close()
```

## Set Protocol Encryption Globally

`Enable_proto_encrypt(is_encrypt)`

* **Introduction**
    Setting protocol encryption can help users protect their requests and returned contents globally. For more information about Protocol Encryption Process, please check [here](../qa/other.md#1479).

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    is_encrypt|bool|Enable encryption or not.


* **Example**

```python
from moomoo import *
SysConfig.enable_proto_encrypt(True)
SysConfig.set_init_rsa_file("conn_key.txt")   # rsa private key file path
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close()
```


## Set the Path of Private Key 

`set_init_rsa_file(file)`

* **Introduction**

    Set the Path of Private Key in moomoo API. For more information about Protocol Encryption Process, please check [here](../qa/other.md#1479).


* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    file|str|Private key file path.

* **Example**

```python
from moomoo import *
SysConfig.enable_proto_encrypt(True)
SysConfig.set_init_rsa_file("conn_key.txt")   # rsa private key file path
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close()
```

## Set Thread Mode

`set_all_thread_daemon(all_daemon)`

* **Introduction**
    Whether to set all internally threads to be daemon threads.
    - If it is set to be daemon threads, then after the main thread exits, the process also exits.  
      For example, when using the real-time callback API, you need to make sure the main thread survives by yourself. Otherwise, when the main thread exits, the process also exits and you will no longer receive the push data.
    - If it is set to a non-daemon thread, the process will not exit after the main thread exits.
      For example, if you do not call close() to close the connection after creating a quote or trade object, the process will not exit even if the main thread exits.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    all_daemon|bool|Whether to set threads to be daemon threads.  (- True：set to daemon threads
  - False：set to non-daemon threads
  - Default is False)

* **Example**

```python
from moomoo import *
SysConfig.set_all_thread_daemon(True)
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
# the process will exit without calling quote_ctx.close(), 
```

## Set Callback

`set_handler(handler)`  

* **Introduction**

    Set asynchronous callback processing object


* **Parameters**
    - handler: callback processing object
        Class|Description
        :-|:-
        SysNotifyHandlerBase|[OpenD notification processing base class](./init.md#787)
        StockQuoteHandlerBase|[Quote processing base class](../quote/update-stock-quote.md)
        OrderBookHandlerBase|[Order book processing base class](../quote/update-order-book.md)
        CurKlineHandlerBase|[Real-time candlestick processing base class](../quote/update-kl.md)
        TickerHandlerBase|[Tick-By-Tick processing base class](../quote/update-ticker.md)
        RTDataHandlerBase|[Time Frame data processing base class](../quote/update-rt.md)
        BrokerHandlerBase|[Broker queue processing base class](../quote/update-broker.md)
        PriceReminderHandlerBase|[Price reminder processing base class](../quote/update-price-reminder.md)
        TradeOrderHandlerBase|[Order processing base class](../trade/update-order.md)
        TradeDealHandlerBase|[Order fill processing base class](../trade/update-order-fill.md)

* **Example**

```python
import time
from moomoo import *
class OrderBookTest(OrderBookHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        ret_code, data = super(OrderBookTest,self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("OrderBookTest: error, msg: %s" % data)
            return RET_ERROR, data
        print("OrderBookTest ", data) # OrderBookTest's own processing logic
        return RET_OK, data
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = OrderBookTest()
quote_ctx.set_handler(handler) # Setting real-time order book callback
quote_ctx.subscribe(['HK.00700'], [SubType.ORDER_BOOK]) # Subscribe to the order book type, OpenD starts to receive pushed data from the server continuously
time.sleep(15) # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close() # Close the current connection, OpenD will automatically cancel the subscription of the corresponding stock in 1 minute
```

## Get Connection ID

`get_sync_conn_id()`  

* **Introduction**

    Get the connection ID, the value will be available after the connection is successfully initialized

* **Return**
    - conn_id: connection ID

* **Example**

```python
from moomoo import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.get_sync_conn_id()
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```

## Event Notification Callback

`SysNotifyHandlerBase`  

* **Introduction**

    Notify OpenD of some important news, such as disconnection, etc.

* **Protocol ID**

    1003

* **Return**

    <table>
        <tr>
            <th>Field</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
        <tr>
            <td>ret</td>
            <td>int</td>
            <td>Returned value. On success, ret == RET_OK. On error, ret != RET_OK.</td>
        </tr>
        <tr>
            <td rowspan="2">data</td>
            <td>tuple</td>
            <td>If ret == RET_OK, <b>event notification data</b> is returned.</td>
        </tr>
        <tr>
            <td>str</td>
            <td>If ret != RET_OK, error description is returned.</td>
        </tr>
    </table>

    * The format of **event notification** data is as follows:
        <table>
            <tr>
                <th>Field</th>
                <th>Type</th>
                <th>Description</th>
            </tr>
            <tr>
                <td>notify_type</td>
                <td>[SysNotifyType](./common.md#5979)</td>
                <td>Notification data type</td>
            </tr>
            <tr>
                <td rowspan="3">sub_type</td>
                <td>[ProgramStatusType](./common.md#9803)</td>
                <td>Subtype. If notify_type == SysNotifyType.PROGRAM_STATUS, program status type is returned.</td>
            </tr>
            <tr>
                <td>[GtwEventType](./common.md#1581)</td>1581
                <td>Subtype. If notify_type == SysNotifyType.GTW_EVENT, OpenD event type is returned.</td>
            </tr>
            <tr>
                <td>0</td>
                <td>If notify_type !=SysNotifyType.PROGRAM_STATUS and notify_type !=SysNotifyType.GTW_EVENT, no useful information is returned.</td>
            </tr>
            <tr>
                <td rowspan="2">msg</td>
                <td rowspan="2">dict</td>
                <td>Event information. If notify_type == SysNotifyType.CONN_STATUS, <b>connection status event information</b> is returned.</td>
            </tr>
            <tr>
                <td>Event information. If notify_type == SysNotifyType.QOT_RIGHT, <b>quote right event information</b> is returned.</td>
            </tr>       
        </table>
        
        * The format of **connection status event information** is as follows(The value of connection status is a bool type, with True for normal, and False for disconnected):
            ```protobuf
            {
                'qot_logined': bool1, 
                'trd_logined': bool2,
            }
            ```        
        * The format of **quote right event information** is as follows(the type of quote right refers to [Quote Right](../quote/quote.md#3959)):
            ```protobuf
            {
                'hk_qot_right': value1,
                'hk_option_qot_right': value2,
                'hk_future_qot_right': value3,
                'us_qot_right': value4,
                'us_option_qot_right': value5,
                'us_future_qot_right': value6,  // deprecated
                'cn_qot_right': value7,
				'us_index_qot_right': value8,
				'us_otc_qot_right': value9,
				'sg_future_qot_right': value10,
				'jp_future_qot_right': value11,
				'us_future_qot_right_cme': value12,
				'us_future_qot_right_cbot': value13,
				'us_future_qot_right_nymex': value14,
				'us_future_qot_right_comex': value15,
				'us_future_qot_right_cboe': value16,
            }
            ```

* **Example**

```python
import time
from moomoo import *

class SysNotifyTest(SysNotifyHandlerBase):
    def on_recv_rsp(self, rsp_str):
        ret_code, data = super(SysNotifyTest, self).on_recv_rsp(rsp_str)
        notify_type, sub_type, msg = data
        if ret_code != RET_OK:
            logger.debug("SysNotifyTest: error, msg: {}".format(msg))
            return RET_ERROR, data
        if (notify_type == SysNotifyType.GTW_EVENT):  #  OpenD event notification
            print("GTW_EVENT, type: {} msg: {}".format(sub_type, msg))
        elif (notify_type == SysNotifyType.PROGRAM_STATUS):  # Notification of change in program status
            print("PROGRAM_STATUS, type: {} msg: {}".format(sub_type, msg))
        elif (notify_type == SysNotifyType.CONN_STATUS):  ## Notification of change in connection status
            print("CONN_STATUS, qot: {}".format(msg['qot_logined']))
            print("CONN_STATUS, trd: {}".format(msg['trd_logined']))
        elif (notify_type == SysNotifyType.QOT_RIGHT):  # Notification of change in quote right
            print("QOT_RIGHT, hk: {}".format(msg['hk_qot_right']))
            print("QOT_RIGHT, hk_option: {}".format(msg['hk_option_qot_right']))
            print("QOT_RIGHT, hk_future: {}".format(msg['hk_future_qot_right']))
            print("QOT_RIGHT, us: {}".format(msg['us_qot_right']))
            print("QOT_RIGHT, us_option: {}".format(msg['us_option_qot_right']))
            print("QOT_RIGHT, us_future: {}".format(msg['us_future_qot_right']))
            print("QOT_RIGHT, cn: {}".format(msg['cn_qot_right']))
            print("QOT_RIGHT, us_index: {}".format(msg['us_index_qot_right']))
			print("QOT_RIGHT, us_otc: {}".format(msg['us_otc_qot_right']))
			print("QOT_RIGHT, sg_future: {}".format(msg['sg_future_qot_right']))
			print("QOT_RIGHT, jp_future: {}".format(msg['jp_future_qot_right']))
            print("QOT_RIGHT, us_future_cme: {}".format(msg['us_future_qot_right_cme']))
            print("QOT_RIGHT, us_future_cbot: {}".format(msg['us_future_qot_right_cbot']))
            print("QOT_RIGHT, us_future_nymex: {}".format(msg['us_future_qot_right_nymex']))
            print("QOT_RIGHT, us_future_comex: {}".format(msg['us_future_qot_right_comex']))
            print("QOT_RIGHT, us_future_cboe: {}".format(msg['us_future_qot_right_cboe']))
        return RET_OK, data

quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
handler = SysNotifyTest()
quote_ctx.set_handler(handler)   # Set real-time swing callback
time.sleep(15)  # Set the script to receive OpenD push duration to 15 seconds
quote_ctx.close()  # After using the connection, remember to close it to prevent the number of connections from running out
```

## Enable console logging of OpenD connection status

`enable_console_log(enable)`

* **Introduction**

    Controls whether connection status between your Python script and OpenD is printed to the console. Optional API.
    Not thread-safe; call at program startup if needed.

* **Parameters**
    Parameter|Type|Description
    :-|:-|:-
    enable|bool|Whether to print connection status to the console  (- True: print
  - False: do not print
  - Default: True)


* **Example**

```python
from moomoo import *
SysConfig.enable_console_log(True)
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
quote_ctx.close()
```

---

# General Definitions

## Interface Result

> **RET_CODE**  

* `RET_OK`

  Success

* `RET_ERROR`  

  Failed

## Protocol Format

> **ProtoFMT**   

* `Protobuf`  

  Google Protobuf

* `Json`
  
  Json

## Packet Encryption Algorithm


## Program Status Type

> **ProgramStatusType**

* `NONE`  

  Unknown

* `LOADED`
  
  The necessary modules have been loaded

* `LOGING`  

  Logging in

* `NEED_PIC_VERIFY_CODE`
  
  Need graphic verification code

* `NEED_PHONE_VERIFY_CODE`

  Need mobile phone verification code

* `LOGIN_FAILED`
  
  Login failed

* `FORCE_UPDATE`

  The client version is too low

* `NESSARY_DATA_PREPARING`
  
  Pulling necessary information

* `NESSARY_DATA_MISSING`

  Missing necessary information

* `UN_AGREE_DISCLAIMER`

  Disclaimer is not agreed

* `READY`

  Ready to use

* `FORCE_LOGOUT`

  OpenD was forced to log out

## OpenD Event Notification Type

> **GtwEventType**

* `LocalCfgLoadFailed`

  Failed to load the local configuration file 

* `APISvrRunFailed`
  
  Failed to run the OpenD monitoring service 

* `ForceUpdate`

  Force upgrade of the OpenD

* `LoginFailed`
  
  Failed to log in to moomoo servers


* `UnAgreeDisclaimer`

  Did not agree to the disclaimer, unable to run

* `LOGIN_FAILED`
  
  Login failed

* `NetCfgMissing`

  Missing network connection configuration

* `KickedOut`
  
  Login kicked offline

* `LoginPwdChanged`
  
  Login password has been changed

* `BanLogin`

  This account is not allowed to log in by moomoo servers

* `NeedPicVerifyCode`
  
  Need graphic verification code

* `NeedPhoneVerifyCode`
  
  Need mobile verification code

* `AppDataNotExist`

  Program package data loss

* `NessaryDataMissing`
  
  The necessary data is not synchronized successfully

* `TradePwdChanged`

  Transaction password change notice

* `EnableDeviceLock`
  
  Need to enable device lock


## System Notification Type

> **SysNotifyType**

* `GTW_EVENT`

  Gateway event

* `PROGRAM_STATUS`
  
  Program status changes

* `CONN_STATUS`

  Status of Connection to moomoo servers has been changed


* `QOT_RIGHT`
  
  Quotes authority changed

## Package Unique Identifier

**PacketID** 

```protobuf
message PacketID
{
  required uint64 connID = 1; //The current TCP connection ID, the unique identifier of a connection, returned by the InitConnect protocol
  required uint32 serialNo = 2; //Increment serial number
}
```

## Program Status

**ProgramStatus**

```protobuf
message ProgramStatus
{
  required ProgramStatusType type = 1; //Current status
  optional string strExtDesc = 2; //Additional description
}
```

---

# Protocol Introduction

moomoo API is an API SDK, encapsulated by moomoo including mainstream programming languages (Python, Java, C #, C++, JavaScript) to make it easy for you to call and reduce the difficulty of trading strategy development.  
This part mainly introduces the underlying protocol of communication between script and OpenD service, which is suitable for users who do not use the above five programming languages.

:::tip Tips
* If you are using a programming language that is one of the five mainstream programming languages mentioned above, you can skip this part.
:::

## Protocol Request Process
* Create a connection
* Initialize the connection
* Request data or receive pushed data
* Send KeepAlive protocol periodically to keep connected

![proto-process](../img/proto_mmprocess.png)


## Protocol Design
The protocol data includes the protocol header and the protocol body. The protocol header is fixed, and the protocol body is determined according to the specific protocol.

### Protocol Header

```
struct APIProtoHeader
{
    u8_t szHeaderFlag[2];
    u32_t nProtoID;
    u8_t nProtoFmtType;
    u8_t nProtoVer;
    u32_t nSerialNo;
    u32_t nBodyLen;
    u8_t arrBodySHA1[20];
    u8_t arrReserved[8];
};
```
Field|Description
:-|:-
szHeaderFlag|Packet header start flag, fixed as "FT"
nProtoID|Protocol ID
nProtoFmtType|Protocol type, 0 for Protobuf, 1 for Json
nProtoVer|Protocol version, used for iterative compatibility, currently 0
nSerialNo|Packet serial number, used to correspond to the request packet and return packet, and it is required to be incremented
nBodyLen|Body length
arrBodySHA1|SHA1 hash value of the original data of the packet body (after decryption)
arrReserved|Reserved 8-byte extension

::: tip Tips
* <font color=Gray> __*u8_t*__ </font> refer to 8-bit unsigned integer, <font color=Gray> __*u32_t*__ </font> refer to 32-bit unsigned integer
* <font color=Gray> __*OpenD*__ </font> internal processing uses <font color=Gray> __*Protobuf*__ </font>, so the protocol format recommends using <font color=Gray> __*Protobuf*__ </font>, to reduce <font color=Gray> __*Json*__ </font> conversion overhead.
* The <font color=Gray> __*nProtoFmtType*__ </font> field specifies the data type of the package body, and the corresponding protocol type will be returned when the package is returned. The data type of the push protocol is specified by the <font color=Gray> __*OpenD*__ </font> configuration file
* <font color=Gray> __*arrBodySHA1*__ </font> is used to verify the consistency of the requested data before and after network transmission, and must be filled in correctly
* The binary stream of the protocol header uses little-endian byte order, that is, generally there is no need to use <font color=Gray> __*ntohl*__ </font> and other related functions to convert the data
:::

### Protocol Body
#### Packet Body Structure of Protobuf Request 
```
message C2S
{
    required int64 req = 1;
}

message Request
{
    required C2S c2s = 1;
}
```

#### Packet Body Structure of Protobuf Response 
```
message S2C
{
    required int64 data = 1;
}

message Response
{
    required int32 retType = 1 [default = -400]; //RetType, result of return
    optional string retMsg = 2;
    optional int32 errCode = 3;
    optional S2C s2c = 4;
}
```

Field|Description
:-|:-
c2s|Request parameter structure
req|Request parameters, actually defined according to the protocol
retType|Request result
retMsg|The reason for the failed request
errCode|The corresponding error code for failed request
s2c|Response data structure, some protocols do not return data if there is no such field
data|Response data, actually defined according to the protocol

::: tip  Tips
* The package body format type request package is specified by <font color=Gray> __*nProtoFmtType*__ </font> field from protocol header, and the <font color=Gray> __*OpenD*__ </font> initiative push format is set in [InitConnect](./init.md#6650).
* The original protocol file format is defined in <font color=Gray> __*Protobuf*__ </font> format. If you need <font color=Gray> __*json*__ </font> format transmission, it is recommended to use the <font color=Gray> __*protobuf3*__ </font> interface to directly convert to <font color=Gray> __*json*__ </font>.
* The enumeration value field definition uses signed integer, and the comment indicates the corresponding enumeration. The enumeration is generally defined in <font color=Gray> __*Common.proto, Qot_Common.proto, Trd_Common.proto*__ </font> files.
* The price, percentage and other data in the protocol are transmitted in floating point type. Direct use will cause accuracy problems. It needs to be rounded according to the accuracy (if not specified in the protocol, the default is 3 decimal places) before use.
:::

## Heartbeat Keep Alive
```protobuf
syntax = "proto2";
package KeepAlive;
option java_package = "com.moomoo.openapi.pb";
option go_package = "github.com/moomooopen/mmapi4go/pb/keepalive";

import "Common.proto";

message C2S
{
	required int64 time = 1; //Greenwich timestamp when the client sends the packet, in seconds
}

message S2C
{
	required int64 time = 1; //Greenwich timestamp when the server returned the packet, in seconds
}

message Request
{
	required C2S c2s = 1;
}

message Response
{
	required int32 retType = 1 [default = -400]; //RetType, return result
	optional string retMsg = 2;
	optional int32 errCode = 3;
	
	optional S2C s2c = 4;
}
```

* **Introduction**

    Heartbeat keep alive

* **Protocol ID**

    1004

* **Introduction**

    According to the heartbeat keeping alive interval returned by the [initialization protocol](./init.md#7571), send the heartbeeat keep alive protocol to OpenD.

## Encrypted Communication Process

* If OpenD is configured with encryption, [InitConnect](../quote/base.md) must use [RSA](../qa/other.md#1479) public key encryption to initialize the connection protocol, and other subsequent protocols use the random key returned by InitConnect for AES encrypted communication.
* The encryption process of OpenD draws on the SSL protocol. Considering that services and applications are generally deployed locally, we simplifies the related processes. OpenD shares the same [RSA](../qa/other.md#1479) private key file with the access Client. Please save and distribute the private key file properly.
* Go to this [URL](http://web.chacuo.net/netrsakeypair) to generate a random [RSA](../qa/other.md#1479) key pair online. The key format must be PCKS#1, the key length can be 512, 1024, and do not set password. Copy and save the generated private key to a file, and then configure the path of the private key file to the **rsa_private_key** configuration item agreed upon in [OpenD Configuration](../opend/opend-cmd.md#149).
* **It is recommended that users who have real trade configure encryption to avoid leakage of account and trade information.**

![encrypt](../img/mmencrypt.png)


## RSA Encryption and Decryption
* [OpenD configuration](../opend/opend-cmd.md#149) Convention **rsa_private_key** is the path of the private key file
* OpenD shares the same private key file with the access client
* RSA encryption and decryption is only used for InitConnect requests, and is used to securely obtain symmetric encryption key of other request protocols
* The [RSA](../qa/other.md#1479) key of OpenD is 1024-bit, the filling method is PKCS1, public key encryption, private key decryption, public key can be generated by private key


### Send Data Encryption
* RSA encryption rules: If the number of key bits is key_size, the maximum length of a single encryption string is (key_size)/8-11. The current number of bits is 1024, and the length of one encryption can be set to 100.
* Divide the plaintext data into one or several segments of up to 100 bytes for encryption, and the final encrypted data is spliced by all segmented encrypted data.

### Receive Data Decryption
* RSA decryption also follows the segmentation rule. For a 1024-bit key, the length of each segment to be decrypted is 128-byte.
* Divide the ciphertext data into one or several segments of up to 128 bytes for decryption, and the final decrypted data is spliced by all segmented decrypted data.

## AES Encryption and Decryption
* The encryption key is returned by the InitConnect protocol
* The ecb encryption mode of AES is used by default.


### Send Data Encryption

* AES encryption requires that the length of the source data must be an integer multiple of 16, so it needs to be aligned with ‘0’ before encryption. Record mod_len for source data length and 16 module.
* Because it is possible to modify the source data before encryption, it is necessary to add a 16-byte padding data block at the end of the encrypted data. The last byte is assigned mod_len, and the remaining bytes are assigned the value '0'. The encrypted data and additional populated data blocks are spliced as the body data to be sent in the end.

### Receive Data Decryption

* For protocol body data, first take out the last byte and record it as mod_len, then truncate the body to the 16-byte padding data block before decrypting it (corresponding to the encrypted padding extra data block logic).
* When mod_len is 0, the above decrypted data is the body data returned by the protocol, otherwise the tail (16-mod_len) length of the data used for filling and alignment needs to be truncated.

![aes](../img/aes.png)

---

# OpenD Related

## Q1: OpenD automatically exited due to failure to complete "Questionnaire Evaluation and Agreement Confirmation"


A: You need to carryout relevant questionnaire evaluation and agreement confirmation before you can use OpenD. Please [go to complete](https://www.moomoo.com/en-us/about/api-disclaimer).


## Q2: OpenD exited due to "the program's own data does not exist"

A: Generally, the copy of the own data fails due to permission problems. You can try to copy the file extracted from <font color=Gray> __*Appdata.dat*__ </font> in the program directory to the program data directory.

* Windows program data directory:`%appdata%/com.moomoo.OpenD/F3CNN`
* Non-windows program data directory:`~/.com.moomoo.OpenD/F3CNN`

## Q3: OpenD service failed to start

A: Please check:
1. Whether there are other programs occupying the configured port;
2. Is there a OpenD configured with the same port already running?

## Q4: How to verify the mobile phone verification code?

A: On the OpenD interface or remotely to the Telnet port, enter the command ʻinput_phone_verify_code -code=123456`.

:::tip Tips
* 123456 is the mobile phone verification code received
* there is a space before '-code=123456'
:::

## Q5: Are other programming languages supported?

A: OpenD provides a socket-based protocol. Currently we provide and maintain Python, C++, Java, C# and JavaScript interfaces, [download entry](https://www.futunn.com/download/OpenAPI?lang=en-US).

If the above languages still cannot meet your needs, you can connect to the Protobuf protocol by yourself.

## Q6: Verify the device lock multiple times on the same device

A: The device ID is randomly generated and stored in the \\com.moomoo.OpenD\\F3CNN\\Device.dat file.

:::tip Tips
1. If the file is deleted or damaged, OpenD will regenerate a new device ID and then verify the device lock.
2. In addition, users of mirror copy deployment need to be aware that if the Device.dat content of multiple machines is the same, it will also cause these machines to verify the device lock multiple times. Delete the Device.dat file to solve it.
:::


## Q7: Does OpenD provide a Docker image?

A: Not currently available.

## Q8: Can one account log in to multiple OpenD?

A: One account can log in to OpenD or other client terminals on multiple machines, and up to 10 OpenD terminals are allowed to log in at the same time. At the same time, there is a restriction of "market kicking", and only one OpenD can obtain the highest authority market. For example, if two terminals log into the same account, there can only be one HK stock LV2 quotation and the other HK stock BMP quotation.

## Q9: How to control the market permissions of OpenD and other clients (desktop and mobile)?

A: In accordance with the regulations of the exchange, there will be a restriction on “market kicking” when multiple terminals are online at the same time, and only one terminal can obtain the highest authority market. The [auto_hold_quote_right](../opend/opend-cmd.md#149) parameter is built-in in the startup parameters of the command line version of OpenD, which is used to flexibly configure market permissions. When this parameter option is enabled, OpenD will automatically retrieve it after the market permission is robbed. If it is robbed again within 10 seconds, other terminals will obtain the highest market quotation authority (OpenD will not rob again).

## Q10: How to give priority to the OpenD market authority?

A:
1. Configure the OpenD startup parameter [auto_hold_quote_right](../opend/opend-cmd.md#149) to 1;
2. Make sure not to grab the highest authority twice in a row within 10 seconds on the mobile or desktop moomoo (login counts once, and click "Restart Quotes" to count the second time).

![quote-right-kick](../img/quote-right-kick.png)

## Q11: How to give priority to the market authority of the mobile terminal (or desktop terminal)?

A: Set OpenD startup parameter [auto_hold_quote_right](../opend/opend-cmd.md#149) to 0, and login with mobile or PC moomoo after OpenD.

## Q12: Use the Visualization OpenD to remember the password to log in. After a long time hang up, it prompts that the connection is disconnected. Do I need to log in again?

A: Using the Visualization OpenD, if you choose to remember the password to log in, you will use the token recorded locally. Due to the time limit of the token, when the token expires, if there is network fluctuation or moomoo background release, it may cause the situation that it cannot be automatically connected after disconnecting from the background. Therefore, if you want visiulization OpenD for a long time to hang up, it is recommended to manually enter the password to log in, and OpenD will automatically handle this situation.


## Q13: How to request official engineers to investigate logs when encountering product defects?

A:
1. Contact Moomoo API developers via QQ/WeChat to facilitate instant communication and file transferation.

2. Detailed description: the time when the error occurred, OpenD version number, moomoo API version number, script language name, interface name or protocol number, short code or screenshot with detailed input and return.

3. If necessary, OpenD log must be provided to facilitate location and confirmation of problems. Transaction issues require info log level, and market issues require debug log level. The log level log_level can be configured in <font color=Gray> __*OpenD.xml*__ </font> [Configure](../opend/opend-cmd.md#149). After configuration, OpenD needs to be restarted to take effect. After the problem recurs, package the log and send it to moomoo R&D personnel.

:::tip Tips
The log path is as follows:

windows: `%appdata%/com.moomoo.OpenD/Log`

Non-windows: `~/.com.moomoo.OpenD/Log`
:::


## Q14: Script cannot connect to OpenD

A: Please try to check first:
1. Whether the port connected by the script is consistent with the port configured by OpenD.
2. Since the upper limit of OpenD connection is 128, is there any useless connection that is not closed?
3. Check whether the listening address is correct. If the script and OpenD are not on the same machine, the OpenD listening address needs to be set to 0.0.0.0.

## Q15: Disconnected after being connected for a while

A: If it is a self-docking protocol, check whether there is a regular heartbeat to maintain the connection.


## Q16: I can't connect to OpenD when I run Python scripts in multiprocessing mode through the multiprocessing module under Linux?

A: After the process is created by default in the Linux/Mac environment, the thread created inside py-moomoo-api in the parent process will disappear in the child process, resulting in an internal program error.
You can use spawn to start the process:

```python
import multiprocessing as mp
mp.set_start_method('spawn')
p = mp.Process(target=func)
```

## Q17: How to log in to two OpenD at the same time on one computer?


A: Visualization OpenD does not support, but Command Line OpenD supports.

1. Unzip the file downloaded from the official website, and copy the entire Command Line OpenD folder (e.g. <font color=Gray> __*moomoo_OpenD_5.2.1408_Windows*__ </font>). Take Windows as an example, other systems can do the same operation.

![en-copied](../img/en-mmcopied.png)

2. Configure two <font color=Gray> __*OpenD.xml*__ </font> files that are placed in two Command Line OpenD folders. Configure items as follow: 

Configuration file 1: api_port = 11111, login_account = Login Account 1, login_pwd = Login Password 1 

Configuration file 2: api_port = 11112, login_account = Login Account 2, login_pwd = Login Password 2 

![order-page](../img/order-page.png)

3. Run the two OpenD.exe.

![en-folder](../img/mmen-folder.png)

4. When calling the interface, note that the parameter `port` (OpenD listening address) should corresponds to the parameter `api_port` in the <font color=Gray> __*OpenD.xml file*__ </font>.  
For example:
```python
from moomoo import *

# Send requests to OpenD logged in account 1
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111, is_encrypt=False)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out

# Send requests to OpenD logged in account 2
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11112, is_encrypt=False)
quote_ctx.close() # After using the connection, remember to close it to prevent the number of connections from running out
```


## Q18: How do I execute the operation and maintenance commands for grabbing permissions through scripts when the market permission is kicked off by other clients?

A:
1. Configure Telnet address and Telnet port.
![telnet_GUI](../img/telnet_GUI.png)
![telnet_CMD](../img/telnet_CMD.jpg)
2. Start OpenD (it will also start Telnet).
3. After finding that the market quotation authority has been robbed, you can refer to the following code example and send the `request_highest_quote_right` command to OpenD via Telnet.
```python
from telnetlib import Telnet
with Telnet('127.0.0.1', 22222) as tn: # Telnet address is: 127.0.0.1, Telnet port is: 22222
     tn.write(b'request_highest_quote_right\r\n')
     reply = b''
     while True:
         msg = tn.read_until(b'\r\n', timeout=0.5)
         reply += msg
         if msg == b'':
             break
     print(reply.decode('gb2312'))
```

<span id="update-failed-qa"></span>


## Q19: OpenD automatic upgrade failed
A:
The automatic update of OpenD failed to be executed by the `update` command. Possible reasons:
- The file is occupied by other processes: you can try to close other  OpenD processes, or restart the system and execute `update` again
If the above still cannot be solved, you can download the update by yourself through [Official Website](https://www.moomoo.com/download/OpenAPI/).

## Q20: Fail to launch the visualization OpenD on ubuntu22？
A: 
When running the visualization OpenD on certain Linux distributions (such as Ubuntu 22.04), you may encounter the error: `dlopen(): error loading libfuse.so.2`. This occurs because libfuse is not installed by default on these systems. Typically you can resolve this issue by installing libfuse manually. For example, you can install it via the commane line on Ubuntu22.04 with:
```
sudo apt update
sudo apt install -y libfuse2
```
Once successfully installed, you will be able to run the visualization OpenD normally. Please refer to 
[https://docs.appimage.org/user-guide/troubleshooting/fuse.html](https://docs.appimage.org/user-guide/troubleshooting/fuse.html) for more details.


## Q21: How to run the command line OpenD in the background on Linux?


A: First, switch to the directory where OpenD is located, configure OpenD.xml, and then execute the following command.
```
nohup ./OpenD &
```

---

# Quote Related

## Q1: Subscription failed

A: When the subscription interface returns an error, there are two common situations.
* Insufficient subscription quota

  Please refer to [Subscription Quota & Historical Candlestick Quota](../intro/authority.md#9123) for the subscription quota rules.

* Insufficient quota right

  The quota right that supports subscription are shown in the following table:
  <table>
    <tr>
      <th> Market </th>
      <th> Contracts </th>
      <th> Quota Right for Subscription </th>
    </tr>
    <tr>
      <td rowspan="3"> HK Market </td>
      <td > Secrities </td>
      <td > LV1, LV2, SF </td>
    </tr>
    <tr>
	    <td> Options</td>
      <td> LV1, LV2</td>
    </tr>
    <tr>
	    <td> Futures</td>
      <td> LV1, LV2</td>
    </tr>
    <tr>
      <td rowspan="3"> US Market </td>
      <td > Secrities </td>
      <td > LV1, LV2 </td>
    </tr>
    <tr>
	    <td> Options</td>
      <td> LV1</td>
    </tr>
    <tr>
	    <td> Futures</td>
      <td> LV1, LV2</td>
    </tr>
    <tr>
      <td > A-Share Market </td>
      <td > Secrities </td>
      <td > LV1 </td>
    </tr>
     <tr>
      <td > Singapore Market </td>
      <td > Stocks </td>
      <td > LV1, LV2 </td>
      </tr>
    <tr>
      <td > Malaysia Market </td>
      <td > Stocks </td>
      <td > LV1, LV2, LV3 </td>
      </tr>
    <tr>
      <td > Japan Market </td>
      <td > Stocks </td>
      <td > LV2, LV3 </td>
      </tr>
</table>

  Please refer to [Quote Right](../intro/authority.html#5331) for the access method. 

  Note: If your account has the above-mantioned quota rights, but the subscription still fails. The possible reason is that [the quota right has been kicked out by other terminals](./opend.html#4390).
   
## Q2: Unsubscribe failed

A: You can unsubscribe after you subscribe for at least one minute.

## Q3: The unsubscribe was successful but the quota was not released

A: The quota is released after all connections are unsubscribed to the market.

For example: Connection A and Connection B are both subscribing to HK.00700's listing data. After Connection A is unsubscribed, because Connection B is still calling HK.00700's listing data, the OpenD quota will not be released until all connections have been unsubscribed the listing data of HK.00700.


## Q4: Will the quota be released if the script connection is closed if the subscription is less than one minute?

A: No. After the connection is closed, the target type whose subscription duration is less than one minute will be automatically unsubscribed after reaching one minute, and the corresponding subscription quota will be released.


## Q5: What is the specific restriction logic for requesting frequency restriction?

A: At most n times within 30 seconds, it means that the interval between the first request and the n+1th request must be greater than 30 seconds.

## Q6: What is the reason why self-selected stocks cannot be added?

A: Please check whether the upper limit is exceeded first, or delete part of the self-selected stocks.

## Q7: Why is the US stock quotation on the API different from quotes on the App?

A: Since U.S. stock trading is distributed across multiple exchanges, Moomoo provides a variety of basic real-time quotes for U.S. stocks. Starting from April 16, Moomoo API will **freely grant** access to real-time U.S. stock market data (free during the promotion). The depth-of-book data for U.S. stocks, which previously required the separate purchase of a market data subscription, has now been adjusted to be free. Moomoo API will integrate two types of U.S. stock quote sources: Nasdaq Basic + TotalView (Nasdaq exchange with 60-depth levels) and NYSE ArcaBook (Arca with 60-depth levels).    

If you notice inconsistencies between the opening price of a U.S. stock on a given day and what is displayed on the App, this is because the upstream real-time market data from Moomoo API combines data from both Nasdaq and NYSE ArcaBook.


## Q8: Where can I buy API quotation cards?

A:
* HK market
   * [HK stocks LV2 advanced market (only non-Chinese mainland IP)](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
   * [HK stock options futures LV2 advanced market (only non-Mainland China IP)](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
   * [HK stocks LV2 + option futures LV2 market (non-Mainland China IP only)](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
   * [HK Stocks Advanced Full Market Quotes (SF Quotes)](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
* US market (**Free for promotion**)
   * [US stocks Nasdaq Basic](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
   * [US stocks Nasdaq Totalview](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)
   * [US options OPRA real-time data](https://qtcard.moomoo.com/index/authority?lang=en-us#reg)


## Q9: Why sometimes, the response of the get interface to obtain real-time data is slow?

A: Because the get interface for real-time data needs to be subscribed first, and it depends on the push to OpenD from the background. If the user uses the get interface to request immediately after subscribing, OpenD may not receive the background push yet. In order to prevent this from happening, the get interface has built-in waiting logic, and the push will be returned to the script immediately after receiving the push within 3 seconds, and empty data will be returned to the script if the background push is not received for more than 3 seconds.
The get interfaces include: get_rt_ticker, get_rt_data, get_cur_kline, get_order_book, get_broker_queue, get_stock_quote. Therefore, when you find that the response of the get interface for obtaining real-time data is relatively slow, you can first check whether it is the cause of no trade data.


## Q10: What kind of data can be obtained after purchasing the API Nasdaq Basic quotation card?

A: Starting from April 16, Nasdaq Basic+TotalView and NYSE ArcaBook market data permissions will be offered free of charge for promotion. The products available for free include securities listed on the Nasdaq, NYSE, and NYSE MKT exchanges (covering U.S.-listed common stocks and ETFs, but excluding U.S. stock futures and options).     
Supported data interfaces include: snapshots, historical candlestick, real-time ticker subscriptions, real-time one-stage subscriptions, real-time candlestick subscriptions, real-time quotation subscriptions, real-time Time Frame subscriptions, and price reminders.

## Q11: How many levels does each market category support?

A:
Quotes category|LV1|LV2|LV3|SF
:-|:-|:-|:-|:-|:-
HK stocks (including Stock, Warrants, bulls and bears, and inbound securities)|/|10|/|full stock + thousand details
HK stock options futures|1|10|/|/
US stocks (including ETF)|1|60|Nasdaq 60 Quotes + Arca 60 Quotes|/
US stock options|1|/|/|/
US futures|/|40|/|/
A-shares|5|/|/|/
Singapore Stocks|1|40|/|/
Malaysia Stocks|3|5|10|/
Japan Stocks|/|10|40|/

## Q12：Why does OpenD still have no quote right after I purchase and activate the quotation card?

A:   

1. The quote right of Moomoo API is not exactly the same as that of APP.  Some quotation cards are only applicable to the APP side. Please confirm that the card you purchased is applicable to OpenD first.
We have listed **all** the quotation cards applicable to Moomoo API in the section *Authorities and Limitations*. Please click [here](../intro/authority.md#9123).


2. After activating the quotation card, your quote right will be effective immediately. Please check **after restarting OpenD**.

## Q13：How to Get Real-time Quotes Through Subscription Interface?
**The First Stop：Subscription**  

Pass the code of underlying security and data type to [Subscription Interface](../quote/sub.md) to finish subscribing.

Subscription interface supports requesting real-time quote, real-time order book, real-time tick-by-tick, real-time Time Frame, real-time candlesticks and real-time broker queue. After a successful subscription, OpenD will continuously receive real-time data from Futo Server.

Attention: The subscription quota is allocated by your total capital, trading amount and trading volume. Please refer to [Subscription Quota & Historical Candlestick Quota](../intro/authority.md#9123) for details. If your subscription quota is not enough, please check if there is any useless subscriptions in the  quota. [Unsubscribe](../quote/sub.md) to release the subscription quota in time.

**The Second Step：Obtain Data**  

We provide two methods to obtain subscribed data from OpenD:

**Methos 1: Real-time data Callback**  
Set corresponding callback functions to process the pushed data asyncronously.

After the callback function is set, OpenD will immediately push the received real-time data to the callback function of the script for processing.

If the underlying security is very active, you may get a large amount of pushed data with high frequency. If you want to slower the push frequency of OpenD, we recommand you to config push frequency(`qot_push_frequency`) in [OpenD Startup Parameter](../quick/opend-base.md#8367)

The interfaces involved in mode 1 include: [Real-time Quote Callback](../quote/update-stock-quote.md), [Real-time Order Book Callback](../quote/update-order-book.md), [Real-time Candlestick Callback](../quote/update-kl.md), [Real-time Time Frame Callback](../quote/update-rt.md), [Real-time Tick-by-Tick Callback](../quote/update-ticker.md), [Real-time Broker Queue Callback](../quote/update-broker.md).

**Method 2: Get Real-time Data**  
Through the access to real-time data interface, you can use scripts to get the latest data received by OpenD. This approach is more flexible, and scripts do not need to deal with massive pushes. As long as  OpenD continues to receive push from servers, the script can obtain the data on demand.

As the data is taken from the pushed data received by OpenD, there is no frequency limit for this type of interface.

The interfaces involved in mode 1 include: [Get Real-time Quote of Securities](../quote/get-stock-quote.md), [Get Real-time Order Book](../quote/get-order-book.md), [Get Real-time Candlestick](../quote/get-kl.md), [Get Real-time Time Frame Data](../quote/get-rt.md), [Get Real-time Tick-by-Tick](../quote/get-ticker.md), [Get Real-time Broker Queue](../quote/get-broker.md).

## Q14：What time period corresponds to each market state？
A: 
<table>
    <tr>
        <th>Market</th>
        <th>Security Type</th>
        <th>Market State</th>
        <th>Time Period (Local time)</th>
    </tr>
    <tr>
        <td rowspan="19" width = "15%">HK Market</td>
	    <td rowspan="8" width = "15%">Securities (including stocks, ETFs, warrants, CBBCs, Inline Warrants)</td>
	    <td> * NONE: No trading</td>
      <td width = "25%"> CST 08:55 - 09:00</td>
    </tr>
    <tr>
	    <td >* ACTION: Pre-market trading</td>
      <td> CST 09:00 - 09:20</td>
    </tr>
    <tr>
	    <td >* WAITING_OPEN: Waiting for opening</td>
      <td> CST 09:20 - 09:30</td>
    </tr>
    <tr>
	    <td>* MORNING: Morning session</td>
      <td> CST 09:30 - 12:00</td>
    </tr>
    <tr>
      <td>* REST: Lunch break</td>
	    <td>CST 12:00 - 13:00</td>
    </tr>
    <tr>
	    <td>* AFTERNOON: Afternoon session</td>
      <td>CST 13:00 - 16:00</td>
    </tr>
    <tr>
	    <td>* HK_CAS: After-hours bidding for HK stocks (The market state corresponding to the addition of CAS mechanism to the Hong Kong stock market)</td>
      <td>CST 16:00 - 16:08</td>
    </tr>
    <tr>
	    <td>* CLOSED: Market closed</td>
      <td>CST 16:08 - 08:55（T+1）</td>
    </tr>
    <tr>
	    <td rowspan="5">Options, Futures (Day Market only)</td>
      <td>* NONE: Waiting for options opening</td>
      <td> CST 08:55 - 09:30</td>
    </tr>
    <tr>
	    <td>* MORNING: Morning session</td>
      <td>CST 09:30 - 12:00</td>
    </tr>
    <tr>
      <td>* REST: Lunch break</td>
	    <td>CST 12:00 - 13:00</td>
    </tr>
    <tr>
	    <td>* AFTERNOON: Afternoon session</td>
      <td>CST 13:00 - 16:00</td>
    </tr>
    <tr>
	    <td>* CLOSED: Market closed</td>
      <td>CST 16:00 - 08:55（T+1）</td>
    </tr>
    <tr>
	    <td rowspan="6">Futures (Day and Night Market)</td>
      <td>* FUTURE_DAY_WAIT_FOR_OPEN: Futures market wait for opening</td>
      <td rowspan="6"> Different trading time for different species</td>
    </tr>
    <tr>
	    <td>* NIGHT_OPEN: Night market trading hours</td>
    </tr>
    <tr>
	    <td>* NIGHT_END: Night market closed</td>
    </tr>
    <tr>
	    <td>* FUTURE_DAY_WAIT_FOR_OPEN: Futures market wait for opening</td>
    </tr>
    <tr>
	    <td>* FUTURE_DAY_OPEN: Day market trading hours</td>
    </tr>
    <tr>
	    <td>* FUTURE_DAY_CLOSE: Day market closed</td>
    </tr>
  <tr>
        <td rowspan="16">US Market</td>
	    <td rowspan="5">Securities (including stocks, ETFs)</td>
	    <td>* PRE_MARKET_BEGIN: Pre-market trading</td>
      <td>EST 04:00 - 09:30</td>
    </tr>
    <tr>
	    <td>* AFTERNOON: Regular trading hours</td>
      <td>EST 09:30 - 16:00</td>
    </tr>
    <tr>
	    <td>* AFTER_HOURS_BEGIN: After-hours trading</td>
      <td>EST 16:00 - 20:00</td>
    </tr>
    <tr>
	    <td>* AFTER_HOURS_END: Market closed of U.S. stock market</td>
      <td>EST 20:00 - 04:00（T+1）</td>
    </tr>
    <tr>
	    <td>* OVERNIGHT: Overnight trading session of U.S. stock market</td>
      <td>EST 20:00 - 04:00（T+1）</td>
    </tr>
    <tr>
	    <td rowspan="6">Options</td>
      <td>* NONE: Waiting for options opening</td>
      <td rowspan="6"> Different trading time for different species</td>
    </tr>
    <tr>
	    <td>* REST：Lunch break</td>
    </tr>
    <tr>
	    <td>* AFTERNOON: Regular trading hours</td>
    </tr>
    <tr>
	    <td>* TRADE_AT_LAST: Late trading hours</td>
    </tr>
    <tr>
	    <td>* NIGHT: Night market trading hours</td>
    </tr>
    <tr>
	    <td>* CLOSED: Market closed</td>
    </tr>
    <tr>
	    <td rowspan="5">Futures</td>
      <td>* NONE: Waiting for U.S. futures opening</td>
      <td rowspan="5"> Different trading time for different species</td>
    </tr>
    <tr>
	    <td>* FUTURE_OPEN: Trading hours of U.S. futures</td>
     </tr>
     <tr>
	    <td>* FUTURE_BREAK: Break of U.S. futures</td>
     </tr>
     <tr>
	    <td>* FUTRUE_BREAK_OVER: Trading hours of U.S. futures after break</td>
     </tr>
     <tr>
	    <td>* FUTURE_CLOSE: Market closed of U.S. futures</td>
     </tr>
    <tr>
        <td rowspan="7">A-share Market</td>
	    <td rowspan="7">Securities (including stocks, ETFs)</td>
	    <td>* NONE: No trading</td>
      <td>CST 08:55 - 09:15</td>
    </tr>
    <tr>
	    <td>* Action: Pre-market trading</td>
      <td>CST 09:15 - 09:25</td>
    </tr>
    <tr>
	    <td>* WAITING_OPEN: Waiting for opening</td>
      <td>CST 09:25 - 09:30</td>
    </tr>
    <tr>
	    <td>* MORNING: Morning session</td>
      <td>CST 09:30 - 11:30</td>
    </tr>
    <tr>
	    <td>* REST: Lunch break</td>
      <td>CST 11:30 - 13:00</td>
    </tr>
    <tr>
	    <td>* AFTERNOON: Afternoon session</td>
      <td>CST 13:00 - 15:00</td>
    </tr>
    <tr>
	    <td>* CLOSED: Market closed</td>
      <td>CST 15:00 - 08:55（T+1）</td>
    </tr>
    <tr>
        <td rowspan="10" width = "15%">Singapore Market</td>
        <td rowspan="5" width = "15%">Securities Products (including Stocks, ETFs, REITs, Structured Warrants, DLCs)</td>
        <td>* WAITING_OPEN: Waiting for Open</td>
        <td>CST 08:30 - 09:00</td>
      </tr>
      <tr>
          <td>* MORNING: Morning Session</td>
        <td>CST 09:00 - 12:00</td>
      </tr>
       <tr>
          <td>* REST: Lunch Break</td>
        <td>CST 12:00 - 13:00</td>
      </tr>
       <tr>
          <td>* AFTERNOON: Afternoon Session</td>
        <td>CST 13:00 - 17:00</td>
      </tr>
       <tr>
          <td>* CLOSED: Closed</td>
        <td>CST 17:16 - 08:30 (T+1)</td>
      </tr>
    <tr>    
	    <td rowspan="5">Futures</td>
	    <td>* FUTURE_DAY_WAIT_FOR_OPEN: Futures market wait for opening</td>
      <td rowspan="5"> Different trading time for different species</td>
    </tr>
     <tr>
	    <td>* NIGHT_OPEN: Night market trading hours</td>
    </tr>
     <tr>
	    <td>* NIGHT_END: Night market closed</td>
    </tr>
     <tr>
	    <td>* FUTURE_DAY_OPEN: Day market trading hours</td>
    </tr>
     <tr>
	    <td>* FUTURE_DAY_CLOSE: Day market closed</td>
    </tr>
    <tr>
        <td rowspan="10" width = "15%">Japanese Market</td>
        <td rowspan="5" width = "15%">Securities Products (including Stocks, ETFs)</td>
          <td>* WAITING_OPEN: Waiting for Open</td>
        <td>JST 07:55 - 09:00</td>
      </tr>
      <tr>
          <td>* MORNING: Morning Session</td>
        <td>JST 09:00 - 11:30</td>
      </tr>
       <tr>
          <td>* REST: Lunch Break</td>
        <td>JST 11:30 - 12:30</td>
      </tr>
       <tr>
          <td>* AFTERNOON: Afternoon Session</td>
        <td>JST 12:30 - 15:30</td>
      </tr>
       <tr>
          <td>* CLOSED: Closed</td>
        <td>JST 15:30 - 07:50 (T+1)</td>
      </tr>
    <tr>    
	    <td rowspan="5">Futures</td>
	    <td>* FUTURE_DAY_WAIT_FOR_OPEN: Futures market wait for opening</td>
      <td>JST 16:25（T-1）- 16:30（T-1）</td>
    </tr>
     <tr>
	    <td>* NIGHT_OPEN: Night market trading hours</td>
      <td>JST 16:30（T-1） - 05:30</td>
    </tr>
     <tr>
	    <td>* NIGHT_END: Night market closed</td>
      <td>JST 05:30 - 08:45</td>
    </tr>
     <tr>
	    <td>* FUTURE_DAY_OPEN: Day market trading hours</td>
      <td>JST 08:45 - 15:15</td>
    </tr>
     <tr>
	    <td>* FUTURE_DAY_CLOSE: Day market closed</td>
      <td>JST 15:15 - 16:25</td>
    </tr>
    <tr>
      <td rowspan="5">Malaysia Market</td>
      <td rowspan="5">Securities Products (including Stocks, ETFs, REITs, Warrants)</td>
          <td>* AUCTION: Pre-market Auction</td>
        <td>CST 08:30 - 09:00</td>
      </tr>
      <tr>
          <td>* MORNING: Morning Session</td>
        <td>CST 09:00 - 12:30</td>
      </tr>
       <tr>
          <td>* REST: Lunch Break</td>
        <td>CST 12:30 - 14:00</td>
      </tr>
       <tr>
          <td>* AFTERNOON: Afternoon Session</td>
        <td>CST 14:30 - 16:45</td>
      </tr>
       <tr>
          <td>* CLOSED: Closed</td>
        <td>CST 17：00 - 08:25 (T+1)</td>
      </tr>
    <tr>
        <td rowspan="3">Cryptocurrency</td>
	    <td rowspan="3">Crypto</td>
	    <td>* NONE：Waiting for trading</td>
      <td rowspan="3">Different trading time for different trading pairs</td>
    </tr>
     <tr>
	    <td>* MORNING：Regular trading time</td>
    </tr>
     <tr>
	    <td>* CLOSED：Market closed</td>
    </tr>
</table>
\* CST, EST, JST represent China time, US Eastern time, and Japan time respectively.

## Q15：Parameter format of stock code.

A：  
* For users with different programming languages, parameter format of stock code is different.
   * **Python users**  
    Format of stock code: `exchange_market.symbol`. The tickers that supports subscriptions are as follows:   
    
<table>
    <tr>
        <th>Market</th>
        <th>Security Type</th>
        <th>exchange_market</th>
        <th>example</th>
    </tr>
    <tr>
        <td rowspan="5">HK market</td>
        <td>Securities (including stocks, ETFs, warrants, CBBCs, Inline Warrants)</td>
        <td>HK</td>
        <td>Tencent：HK.00700</td>
    </tr>
    <tr>
        <td>Indices</td>
        <td>HK</td>
        <td>Hang Seng Index：HK.800000</td>
    </tr>  
    <tr>
        <td>Futures</td>
        <td>HK</td>
        <td>HSI Futures(JUN6)：HK.HSI2606</td>
    </tr>
    <tr>
        <td>Options</td>
        <td>HK</td>
        <td>* HK stock TCH 260330 450.00C：HK.TCH260330C450000 <br> * HK Index HSI 260330 24000.00C：HK.HSI260330C24000000</td>
    </tr>
    <tr>
        <td>Plates  (get_plate_list first) </td>
        <td>HK</td>
        <td>AI applications stocks：HK.LIST24037</td>
    </tr>
    <tr>
        <td rowspan="5">US market</td>
        <td>Securities (Covers NYSE, NYSE-American and Nasdaq listed equities, ETFs)</td>
        <td>US</td>
        <td>NVDA：US.NVDA</td>
    </tr>
    <tr>
        <td>Options</td>
        <td>US</td>
        <td>* US stock NVDA 260330 160.00C：US.NVDA260330C160000 <br> * US Index SPXW 260330 6330.00C: US..SPXW260330C6330000</td>
    </tr>
    <tr>
        <td>Futures</td>
        <td>US</td>
        <td>E-mini S&P 500 Futures(JUN6)：US.ES2606</td>
    </tr>
    <tr>
        <td>Plates  (Recommend to  get_plate_list first) </td>
        <td>US</td>
        <td>Semiconductors：US.LIST20077</td>
    </tr>
    <tr>
        <td>Indices (not available yet)</td>
        <td>US</td>
        <td>S&P 500：US..SPX</td>
    </tr>
    <tr>
        <td rowspan="3">A-share market</td>
        <td>Securities (including stocks, ETFs)</td>
        <td>SH/SZ</td>
        <td>Kweichow Moutai：SH.600519</td>
    </tr>
    <tr>
        <td>Indices</td>
        <td>SH/SZ</td>
        <td>SSE Composite Index：SH.000001</td>
    </tr>
    <tr>
        <td>Plates  (Recommend to  get_plate_list first) </td>
        <td>SH/SZ</td>
        <td>Automotive Electronics Concept：SH.LIST0301</td>
    </tr>
    <tr>
        <td rowspan="2">SG market</td>
        <td>Securities Products (including Stocks, ETFs, REITs, Structured Warrants, DLCs)</td>
        <td>SG</td>
        <td>Singapore Airlines: SG.C6L</td>
    </tr>
    <tr>
        <td>Futures (not available yet)</td>
        <td>SG</td>
        <td>FTSE China A50 Index Futures(JUN6)：SG.CN2606</td>
    </tr>
    <tr>
        <td rowspan="2">JP market</td>
        <td>Securities Products (including Stocks, ETFs)</td>
        <td>JP</td>
        <td>Nintendo: JP.7974</td>
    </tr>
    <tr>
        <td>Futures (not available yet)</td>
        <td>JP</td>
        <td>OSE Nikkei 225 Futures(JUN6)：JP.NK2252606</td>
    </tr>
     <tr>
          <td rowspan="1">Malaysia Market</td>
          <td>Securities Products (including Stocks, ETFs, REITs, Warrants)</td>
          <td>MY</td>
          <td>MAYBANK: MY.1155</td>
    </tr>
    <tr>
        <td rowspan="1">Crypto</td>
        <td>Crypto indices & trading pairs</td>
        <td>CC</td>
        <td>* Indices：CC.BTC <br> * Trading pairs: CC.BTCUSD</td>
    </tr> 
    </table>


   * **Non-Python users**   
    For stock structure, refer to [Security](../quote/quote.html#5792).  
    For example: Tencent. Parameter `market` should be passed in QotMarket_HK_Security, parameter `code` should be passed in '00700'.

* Quick inquiries.
   View the code and market through APP: Quotes > Watchlists > All.   
   For Quote Market, refer to [here](../quote/quote.html#456).   
    ![code](../img/code.png)


## Q16：Stock Price Adjustment

A：  
### Overview
[Price adjustment](../quote/get-rehab.html#1938) refers to adjusting stock price and trading volume after corporate actions, so that the price chart can better represent actual price moves and trading volume.   
Corporate actions such as stock split, reverse stock split, bonus issue, rights issue, allotment, secondary offering, and dividend payment can affect the stock price. Price adjustment eliminates the impact of corporate actions on stock price and trading volume, and maintains the continuity of the stock price moves.    

:::tip Tips
* The information on this page is mainly intended for the China A-share market.   
:::

### Glossary
- Corporate action: Actions on equity and stock conducted by a listed company that affect the company's stock price and number of shares.
- Default adjustment: Keep the current stock price unchanged, and use it as the benchmark to re-calculate all previous stock prices.
- Cumulative adjustment: Keep the stock price before the earliest corporate action unchanged, and use it as the benchmark to re-calculate all future stock prices.
- Price adjustment factor: The ratio used to re-calculate the adjusted and cumulative stock prices and number of shares after a corporate action. There are two types of price adjustment factors: the default adjustment factor for calculating the adjusted price and the cumulative adjustment factor for calculating the cumulative price.
- Ex-div and pay date: The next trading day of the registration date. The stock exchange must calculate the adjusted stock price before market open on the ex-and-pay date. It is also the date on which dividends are distributed to shareholders and changes in the number of shares take place.

### Price Adjustment Methods
There are two price adjustment methods: two-step method and continuous multiplication. Moomoo API uses different adjustment methods for different markets.   
- Two-step method: The stock price is adjussted based on corporate actions; there are 2 factors in this method: factor A for cash dividends and factor B for all other corporate actions.
- Continuous multiplication: The stock price is adjusted the continuously multiplying the adjustment factors. This method can be seen as a special case of two-step method with factor B as 0.

::: tip Tips:
* API uses continuous multiplication for calculating the adjusted price of US stocks, with the price adjustment factor B set to 0. 
* API uses two-step method for stocks other than US stocks (China A-shares, Hong Kong stocks, Singapore stocks, etc.) and for calculating the cumulative price of US stocks. 
:::

### Calculation Formulae

#### Single Adjustment
- Default adjustment:   
Adjusted price = Actual price × Default adjustment factor A + Default adjustment factor B
- Cumulative adjustment:    
Cumulative price = Actual price × Cumulative adjustment factor A + Cumulative adjustment factor B

#### Multiple Price Adjustments
- Default adjustment: In chronological order, select the adjustment factors later than the adjustment date, and first use earlier adjustment factors for calculation. Take a double adjustment as an example:   

![code](../img/forward_fomula_en.png) 

- Cumulative adjustment: In reverse chronological order, select the adjustment factors earlier than or on the calculation date, and first use later adjustment factors for calculation. Take a double adjustment as an example:   

![code](../img/backward_fomula_en.png) 

### Examples
#### Example of a single adjustment
Take the stock of Muyuan Foods as an example:   
- Screening weighting factors are as follows:   

Ex-Div and Pay Date | Stock Symbol | Corporate Action Details | Default Adjustment Factor A | Default Adjustment Factor B
:-|:-|:-|:-|:-
06/03/2021 | SZ.002714 | 10-share dividends: 4 shares and ￥14.61 (tax included) | 0.71429 | -1.04357

- Data on actual price:   

Date | Stock Symbol | Actual Closing Price
:-|:-|:-
06/02/2021 | SZ.002714 | 93.11
06/03/2021 | SZ.002714 | 66.25

- Data on adjusted prices:    

Date | Stock Symbol | Adjusted Closing Price
:-|:-|:-
06/02/2021 | SZ.002714 | 65.4639719
06/03/2021 | SZ.002714 | 66.25

- Method for calculating adjusted prices:   
Muyuan Foods conducted a stock split and paid cash dividends on 2021/06/03 (4 shares and ￥14.61 for every 10 shares owned), and here is how to calculate the adjusted closing price on 06/02/2021: Adjusted price (65.4639719 ) = Actual price (93.11) × Default adjustment factor A (0.71429) + Default adjustment factor B (-1.04357)

![code](../img/adjusted_factor_example_en.png) 

#### Example of multiple cumulative adjustment
Following on the previous example, here is how to calculate the cumulative price of  Muyuan Foods on 06/02/2021:    
- Adjustment factors are as follows:    

Ex-Date | Stock Symbol | Corporate Action Details | Cumulative Factor A | Cumulative Factor B 
:-|:-|:-|:-|:-|
07/04/2014 | SZ.002714 | 10-share dividends: ￥2.34 (tax included) | 1 | 0.234
06/10/2015 | SZ.002714 | 10-share dividends: 10 shares and ￥0.61 tax included) | 2 | 0.061
07/08/2016 | SZ.002714 | 10-share dividends: 10 shares and ￥3.53 tax included) (tax included) | 2 | 0.353
07/11/2017 | SZ.002714 | 10-share dividends: 8 shares and ￥6.9 (tax included) | 1.8 | 0.69
07/03/2018 | SZ.002714 | 10-share dividends: ￥6.91 (tax included)  | 1 | 0.691
07/04/2019 | SZ.002714 | 10-share dividends: ￥0.5 (tax included) | 1 | 0.05
06/04/2020 | SZ.002714 | 10-share dividends: 7 shares and ￥5.5 (tax included) | 1.7 | 0.55

- Data on actual prices:    

Date | Stock Symbol | Actual Price
:-|:-|:-
06/02/2021 | SZ.002714 | 93.11

- Data on cumulative prices:    

Date | Stock Symbol | Cumulative Price
:-|:-|:-
06/02/2021 | SZ.002714 | 1152.7226

- Method for calculating cumulative prices:   
To calculate the cumulative price of Muyuan Foods on June 2, 2021, all the corporate actions by June 2, 2021 need to be taken into account. The detailed calculations are as follows:

![code](../img/backward_example.jpg)


## Q17：Crypto Multi-Broker Market Data

#### 1. Why does crypto market data differ between brokers?
A： Different brokers source their market data from different upstream providers, so the same trading pair may show price differences across brokers. API supports switching market data sources based on your broker, ensuring that the quotes you see are consistent with your actual trading accounts.

#### 2. Which data source is used if I don't specify a broker?
A：When no broker is specified, API defaults to displaying market data from the primary recommended broker's upstream source.

#### 3. I have multiple broker accounts that support crypto trading. How should I choose?
A：It is recommended to select the broker that corresponds to your actual trading account when viewing market data. This ensures that the quotes you see match the execution prices when placing orders, avoiding discrepancies caused by different data sources.

---

# Transaction Related

## Q1: How to use paper trading?

A: 
### Overview
Paper trading is a simulation that allows you to practice trading without the risk of using real money. 

#### Trading time for parper trading
Supported trading hours: Regular trading hours (all markets), RTH for US stock, ETH for US stock (only supported for US stock margin paper trading accounts)    
Unsupported trading hours: OVERNIGHT for US stock, HK market and China A-shares market Opening and Closing Auction     
For details, please click [Rules of paper trading](https://www.moomoo.com/us/support/topic3_15?from_platform=4&lang=en-us).

#### Categories supported
For categories that Moomoo API supports by paper trading, please click [here](../intro/intro.md#8029).

#### Unlock Trade
Different from live trading, you do not need to unlock the account to place orders or modify or cancel orders when using paper trading.

#### Orders
1. Order Types: limit order and market order.  
2. Modify Order Operation: Paper trading does not support enabling, disabling, and deleting the order, but supports modifying and canceling the order.
3. Deals: Paper trading does not support deals related operations, including [Get today's deals](../trade/get-order-fill-list.md#9411), [Get historical deals](../trade/get-history-order-fill-list.md#6628), and [Respond to the transaction push](../trade/update-order-fill.md#4428).
4. Valid Period: Paper trading only supports good for day order when setting valid period.
5. Short Selling: Options and futures support short selling. Only US stocks support short selling. 
6. Paper trading accounts do not support querying order fees.
7. Paper trading accounts do not support querying cash flow records.
8. For combined options orders, position queries are supported, but combined order queries are not yet available.


#### Platform
1. Mobile clients: Me — Paper Trading.

![sim-page](../img/en-sim-page.png)

2. Desktop clients: Left side tab *Paper* .

![sim-page](../img/en-create-sim-account.png)

3. Web clients: [Paper Trading Website](https://www.moomoo.com/us/support/topic3_15?from_platform=4&lang=en-us).

4. Moomoo API: When calling the interface, set the parameter trading environment to the simulated environment. Click [How to use paper trading through Moomoo API](../qa/trade.md#4514-2) for detail.

::: tip Tips
* The four platforms shown above use the same paper trading accounts.
:::


### How to use paper trading through Moomoo API?

#### Create Connection
Firstly, [create the corresponding connection](../trade/base.md#8155). When the underlyings are stocks or options, please use  `OpenSecTradeContext`. When the underlyings are futures, please use `OpenFutureTradeContext`.

#### Get the List of Trading Accounts  
Use the interface [Get the List of Trading Accounts](../trade/get-acc-list.md#9665) to view trading accounts (including paper trading accounts and live trading accounts). Take Python as an example: When the returned parameter `trd_env` is `SIMULATE`, it means the corresponding account is a paper trading account.

To obtain the HK Paper Trading accounts, specify filter_trdmarket as TrdMarket.HK. This will return two paper trading accounts. The account with sim_acc_type = STOCK represents a HK paper trading account, while sim_acc_type = OPTION refers to a HK stock options paper trading account, and sim_acc_type = FUTURES indicates a HK futures paper trading account.   

To obtain the US Paper Trading accounts, specify filter_trdmarket as TrdMarket.US. An account with sim_acc_type = STOCK_AND_OPTION represents the US margin paper trading account, which allows the stock and options trading. An account with sim_acc_type = FUTURES represents a US futures paper trading account.

* **Example: Stocks and Options**
```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUSECURITIES)
#trd_ctx = OpenFutureTradeContext(host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.get_acc_list()
if ret == RET_OK:
    print(data)
    print(data['acc_id'][0])  # get the first account id
    print(data['acc_id'].values.tolist())  # convert to list format
else:
    print('get_acc_list error: ', data)
trd_ctx.close()
```

* **Output**
```python
               acc_id   trd_env acc_type          card_num   security_firm  \
0  281756480572583411      REAL   MARGIN  1001318721909873  FUTUSECURITIES   
1             9053218  SIMULATE     CASH               N/A             N/A   
2             9048221  SIMULATE   MARGIN               N/A             N/A   

  sim_acc_type  trdmarket_auth  
0          N/A  [HK, US, HKCC]  
1        STOCK            [HK]  
2       OPTION            [HK] 
```
::: tip Tips
* In paper trading, stock accounts and options accounts are distinguished. Stock accounts can only trade stocks, and options accounts can only trade options; take Python as an example: `sim_acc_type` in the returned field is `STOCK`, which means stock account; `OPTION` means option account.
:::
 
* **Example: Futures**
```python
from moomoo import *
#trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUSECURITIES)
trd_ctx = OpenFutureTradeContext(host='127.0.0.1', port=11111, is_encrypt=None, security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.get_acc_list()
if ret == RET_OK:
    print(data)
    print(data['acc_id'][0])  # get the first account id
    print(data['acc_id'].values.tolist())  # convert to list format
else:
    print('get_acc_list error: ', data)
trd_ctx.close()
```

* **Output**
```python
    acc_id   trd_env acc_type card_num security_firm sim_acc_type  \
0  9497808  SIMULATE   MARGIN      N/A           N/A      FUTURES   
1  9497809  SIMULATE   MARGIN      N/A           N/A      FUTURES   
2  9497810  SIMULATE   MARGIN      N/A           N/A      FUTURES   
3  9497811  SIMULATE   MARGIN      N/A           N/A      FUTURES   

          trdmarket_auth  
0  [FUTURES_SIMULATE_HK]  
1  [FUTURES_SIMULATE_US]  
2  [FUTURES_SIMULATE_SG]  
3  [FUTURES_SIMULATE_JP]  
```  

#### Place Orders
When using the interface [Place Orders](../trade/place-order.md), set the trading environment to the simulated environment. Take Python as an example: `trd_env = TrdEnv.SIMULATE`.

* **Example**
```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.place_order(price=510.0, qty=100, code="HK.00700", trd_side=TrdSide.BUY, trd_env=TrdEnv.SIMULATE)
if ret == RET_OK:
    print(data)
else:
    print('place_order error: ', data)
trd_ctx.close()
```
* **Output**
```python
	code	stock_name	trd_side	order_type	order_status	order_id	qty	price	create_time	updated_time	dealt_qty	dealt_avg_price	last_err_msg	remark	time_in_force	fill_outside_rth
0	HK.00700	Tencent	BUY	NORMAL	SUBMITTING	4642000476506964749	100.0	510.0	2021-10-09 11:34:54	2021-10-09 11:34:54	0.0	0.0			DAY	N/A
```

#### Modify or Cancel Orders
When using the Interface [Modify or Cancel Orders](../trade/modify-order.md), set the trading environment to the simulated environment. Take Python as an example: `trd_env = TrdEnv.SIMULATE`.

* **Example**
```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUSECURITIES)
order_id = "4642000476506964749"
ret, data = trd_ctx.modify_order(ModifyOrderOp.CANCEL, order_id, 0, 0, trd_env=TrdEnv.SIMULATE)
if ret == RET_OK:
    print(data)
else:
    print('modify_order error: ', data)
trd_ctx.close()
```
* **Output**
```python
    trd_env             order_id
0  SIMULATE  4642000476506964749
```

#### Get Historical Orders
When using the Interface [Get Historical Orders](../trade/get-history-order-list.md), set the trading environment to the simulated environment. Take Python as an example: `trd_env = TrdEnv.SIMULATE`.


* **Example**
```python
from moomoo import *
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK, host='127.0.0.1', port=11111, security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.history_order_list_query(trd_env=TrdEnv.SIMULATE)
if ret == RET_OK:
    print(data)
else:
    print('history_order_list_query error: ', data)
trd_ctx.close()
```
* **Output**
```python
	code	stock_name	trd_side	order_type	order_status	order_id	qty	price	create_time	updated_time	dealt_qty	dealt_avg_price	last_err_msg	remark	time_in_force	fill_outside_rth
0	HK.00700	Tencent	BUY	ABSOLUTE_LIMIT	CANCELLED_ALL	4642000476506964749	100.0	510.0	2021-10-09 11:34:54	2021-10-09 11:37:08	0.0	0.0			DAY	N/A
```

### How to reset the paper trading account?
Currently, Moomoo API does not support resetting the paper trading account. You can use the reset card on the mobile clients. After the reset, net assets would be restored to the initial value and the historical orders would be emptied.

#### Specific process
Modify clients: Me — Paper Trading — My Icon — My Card — Reset Card
![sim-page](../img/en-sim-reset.png)

### How to reset the paper trading account?
Currently, Moomoo API does not support resetting the paper trading account. You can use the reset card on the mobile clients. After the reset, net assets would be restored to the initial value and the historical orders would be emptied.


#### Specific process
Modify clients: Me — Paper Trading — My Icon — My Card — Reset Card
![sim-page](../img/en-sim-reset.png)

## Q2: If support A-share trading or not?

A: Paper trading supports A-share trading. However, real trade can only be used to trade some A-shares through A-shares connect. For details, please refer to [List of HKCC](https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Eligible-Stocks/View-All-Eligible-Securities?sc_lang=en).

## Q3: Trading directions supported by each market

A: Except for futures, other stocks only support the two trading directions of BUY and SELL. In the case of a short position, SELL is passed in, and the direction of the resulting order is short selling.

## Q4: Order types supported in each market in real environment

A:
<table style="font-size:14px;">
    <tr>
        <th>Market</th>
        <th>Variety</th>
        <th>Limit Orders</th>
        <th>Market Orders</th>
        <th>At-auction Limit Orders</th>
        <th>At-auction Market Orders</th>
        <th>Absolute Limit Orders</th>
        <th>Special Limit Orders</th>
        <th>AON Special Limit Orders</th>
        <th>Stop Orders</th>
        <th>Stop Limit Orders</th>
        <th>Market if Touched Orders</th>
        <th>Limit if Touched Orders</th>
        <th>Trailing Stop Orders</th>
        <th>Trailing Stop Limit Orders</th>
    </tr>
    <tr>
        <td rowspan="3">HK</td>
        <td>Securities (including stocks, ETFs, warrants, CBBCs, Inline Warrants)</td>
        <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td>Options</td>
        <td>✓</td> <td>X</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>X</td> <td>✓</td> <td>X</td> <td>✓</td> <td>X</td> <td>✓</td>
    </tr>
    <tr>
        <td>Futures</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td rowspan="3">US</td>
        <td>Securities (including stocks, ETFs)</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td>Options</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td>Futures</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td>HKCC</td>
        <td>Securities (including stocks, ETFs)</td>
        <td>✓</td> <td>X</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>X</td> <td>✓</td> <td>X</td> <td>✓</td> <td>X</td> <td>✓</td>
    </tr>
    <tr>
        <td>Singapore</td>
        <td>Futures</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
    <tr>
        <td>Japanese</td>
        <td>Futures</td>
        <td>✓</td> <td>✓</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td>
    </tr>
</table>

## Q5: Order operations supported by each market

A:
* HK stocks support order modification, cancellation, entry into force, invalidation, and deletion
* US stocks only support order modification and cancellation
* HKCC only supports cancellation of orders
* Futures supports order modification, cancellation, and deletion

## Q6: How to use OpenD startup parameter future_trade_api_time_zone?

A: Since the types of futures supported for trading account are distributed in multiple exchanges around the world, and the time zones of the exchanges are different, the time display of the futures trading API has become a problem.
The future_trade_api_time_zone parameter has been added to the OpenD startup parameters, allowing futures traders in different regions of the world to flexibly specify the time zone. The default time zone is UTC+8. If you are more accustomed to Eastern Time, you only need to configure this parameter to UTC-5.
:::tip Tips
+ This parameter is only valid for futures trading interface objects. The time zone of HK stock trading, US stock trading, and HKCC trading interface objects is still displayed in accordance with the time zone of the exchange.
+ The interfaces affected by this parameter include: responding to order push callbacks, responding to transaction push callbacks, querying today's orders, querying historical orders, querying current transactions, querying historical transactions, and placing orders.
:::

## Q7: Can I see the order placed through API, in APP?

A：Yes, you can.   
After the order is successfully placed through Moomoo API, you can view today's orders, order status change in the trade page of APP, and you can also receive **Order Notice** in the APP.

![download-page](../img/download-mmpage.png)


## Q8: Which trading targets support Off-Market order?

A：All orders can only be filled during the market opening period.  
Orders made outside market hours and extended hours trading are queued and fulfilled either at or near the beginning of extended hours trading or at or near the market open, according to your instructions. These orders may be named as off market orders or overnight order.
Moomoo API supports Off-Market order for a part of trading targets (APP supports much more trading targets' Off-Market order), as follows:

<table>
    <tr>
        <th rowspan="2">Market</th>
        <th rowspan="2">Contracts</th>
        <th rowspan="2">Paper Trading</th>
        <th colspan="7">Live Trading</th>
    </tr>
    <tr>
        <th>FUTU HK</th>
        <th>Moomoo Financial Inc.</th>
        <th>Moomoo Financial Singapore Pte. Ltd.</th>
        <th>Moomoo AU</th>
        <th>Moomoo MY</th>
        <th>Moomoo CA</th>
        <th>Moomoo JP</th>
    </tr>
    <tr>
        <td rowspan="3">HK Market</td>
	    <td>Securities<br>(including stocks, ETFs, warrants, CBBCs, Inline Warrants)</td>
	    <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Options</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="3">US Market</td>
	    <td>Securities (including stocks, ETFs)</td>
	    <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
    </tr>
    <tr>
        <td>Options</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
    </tr>
    <tr>
	    <td>Futures</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="2">A-share Market</td>
	    <td>HKCC stocks</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td>Non-HKCC stocks</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td rowspan="1">Singapore Market</td>
	    <td>Futures</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td rowspan="2">Japanese Market</td>
        <td>Securities (including stocks, ETFs, REITS)</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
        <td>Futures</td>
        <td align="center">✓</td>
        <td align="center">✓</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td rowspan="1">Australian Market</td>
        <td>Securities (including stocks, ETFs)</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
    <tr>
	    <td rowspan="1">Canadian Market</td>
        <td>Securities</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
        <td align="center">X</td>
    </tr>
</table>

::: tip Tip
- ✓：support Off-Market order
- X：do not support Off-Market order（or non-tradable）
:::

## Q9: For each order type，mandatory parameters of PlaceOrder and broker limits for the single order.
A1: Mandatory parameters of PlaceOrder.

<table style="font-size:14px;">
    <tr>
        <th>Parameters</th>
        <th>Limit Orders</th>
        <th>Market Orders</th>
        <th>At-auction Limit Orders</th>
        <th>At-auction Market Orders</th>
        <th>Absolute Limit Orders</th>
        <th>Special Limit Orders</th>
        <th>AON Special Limit Orders</th>
        <th>Stop Orders</th>
        <th>Stop Limit Orders</th>
        <th>Market if Touched Orders</th>
        <th>Limit if Touched Orders</th>
        <th>Trailing Stop Orders</th>
        <th>Trailing Stop Limit Orders</th>
    </tr>
    <tr>
        <td>price</td>
        <td>✓</td> <td></td> <td>✓</td> <td> </td> <td>✓</td> <td>✓</td> <td>✓</td>  <td></td><td>✓</td> <td></td> <td>✓</td><td> </td><td> </td>
    </tr>
    <tr>
        <td>qty</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>code</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trd_side</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>order_type</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trd_env</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>aux_price</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td> </td><td> </td>
    </tr>
    <tr>
        <td>trail_type</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trail_value</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trail_spread</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td> </td><td>✓</td>
    </tr>
</table>

`Python users` should note that, [place_order](../trade/place-order.html) does not set a default value for price. For the five types of orders mentioned above, you still need to pass in price, which can be any value.

A2: The broker sets limits on shares or amounts for single orders of various trading products. Exceeding these limits may result in order failures. See the table below for details.
<table style="font-size:14px;">
    <tr>
        <th>Broker</th>
        <th>Product</th>
        <th>Quantity Limit Per Order</th>
        <th>Amount Limit Per Order</th>
    </tr>
    <tr>
        <td rowspan="3">FUTU HK</td>
        <td>China A-Shares</td>
        <td>1,000,000 Shares</td>
        <td>￥5,000,000</td>
    </tr>
    <tr>
        <td>US Stocks</td>
        <td>500,000 Shares</td>
        <td>$5,000,000</td>
    </tr>
    <tr>
        <td>Hong Kong Stock Futures or Options</td>
        <td>3,000 Contracts</td>
        <td>Unlimited</td>
    </tr>
    <tr>
        <td>moomoo US</td>
        <td>US Stocks</td>
        <td>500,000 Shares</td>
        <td>$10,000,000</td>
    </tr>
    <tr>
        <td>moomoo SG</td>
        <td>US Stocks</td>
        <td>500,000 Shares</td>
        <td>$5,000,000</td>
    </tr>
    <tr>
        <td>moomoo AU</td>
        <td>US Stocks</td>
        <td>Unlimited</td>
        <td>Unlimited</td>
    </tr>
</table>

## Q10: For each order type, when modifying the order, mandatory parameters of ModifyOrder as follows.

<table style="font-size:14px;">
    <tr>
        <th>Parameters</th>
        <th>Limit Orders</th>
        <th>Market Orders</th>
        <th>At-auction Limit Orders</th>
        <th>At-auction Market Orders</th>
        <th>Absolute Limit Orders</th>
        <th>Special Limit Orders</th>
        <th>AON Special Limit Orders</th>
        <th>Stop Orders</th>
        <th>Stop Limit Orders</th>
        <th>Market if Touched Orders</th>
        <th>Limit if Touched Orders</th>
        <th>Trailing Stop Orders</th>
        <th>Trailing Stop Limit Orders</th>
    </tr>
    <tr>
        <td>modify_order_op</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>order_id</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>price</td>
        <td>✓</td> <td></td> <td>✓</td> <td> </td> <td>✓</td> <td>✓</td> <td>✓</td>  <td></td><td>✓</td> <td></td> <td>✓</td><td> </td><td> </td>
    </tr>
    <tr>
        <td>qty</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trd_env</td>
        <td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>aux_price</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td>✓</td><td>✓</td><td>✓</td><td>✓</td> <td> </td><td> </td>
    </tr>
    <tr>
        <td>trail_type</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trail_value</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td>✓</td><td>✓</td>
    </tr>
    <tr>
        <td>trail_spread</td>
        <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> </td><td> </td><td> </td><td> </td><td> </td> <td> </td><td>✓</td>
    </tr>
</table>

`Python users` should note that, [modify_order](../trade/modify-order.html) does not set a default value for price. For the five types of orders mentioned above, you still need to pass in price, which can be any value.


## Q11: The Trade API returns "The current securities account has not yet agreed to the disclaimer."?
A:  
Click the link below to confirm the agreement, and restart OpenD to use trading functions normally.
Securities Firm|Aggrement Link
:-|:-|:-
FUTU HK|[Click here](https://risk-disclosure.futuhk.com/index?agreementNo=HKOT0015)
Moomoo US|[Click here](https://risk-disclosure.us.moomoo.com/index?agreementNo=USOT0027)
Moomoo SG|[Click here](https://risk-disclosure.sg.moomoo.com/index?agreementNo=SGOT0015)
Moomoo AU|[Click here](https://risk-disclosure.au.moomoo.com/index?agreementNo=AUOT0025)
Moomoo CA|[Click here](https://risk-disclosure.ca.moomoo.com/index?agreementNo=CAOT0117)
Moomoo MY|[Click here](https://risk-disclosure.my.moomoo.com/index?agreementNo=MYOT0066)
Moomoo JP|[Click here](https://risk-disclosure.jp.moomoo.com/index?agreementNo=JPOT0140)


## Q12: Pattern Day Trader (PDT)
### Overview

When clients use moomoo US accounts for intraday trading, they are subject to regulations by the US Financial Industry Regulatory Authority (FINRA). This is a regulatory requirement for US brokers and has nothing to do with the market to which a stock being traded belongs. The trading accounts of brokers in other countries or regions, such as moomoo HK and moomoo SG accounts, are not subject to this restriction. If a client conducts over 3 day trades in any 5 consecutive trading days, the client will be labelled as a pattern day trader (PDT).     
For more details, refer to [Help Center - Day Trade Rules](https://www.moomoo.com/us/support/topic4_5?from_platform=4&lang=en-us).

### Day Trading Flowchart 
![PDT_process](../img/PDT_process.png) 

### How to turn off "Pattern Day Trade Protection", if I'm willing to be labelled as a PDT and do not want the quant trading program to be interrupted?
A:  
To prevent you from being unintentionally labelled as a PDT, the server will automatically intercept your 4th day trade in any 5 consecutive trading days. If you are willing to be labelled as a PDT and do not want the server to intercept your trade, you can take the following step:  
Via [Command Line OpenD](../opend/opend-cmd.html), modify the value of the startup parameter "pdt_protection" to "0".  

![US_para](../img/us_mmpara.png)
NOTE: You will not be able to establish new positions when you are labelled as a PDT and your account equity is below $25000.


### How to turn off the Day-Trading Call Warning?
A:  
Once you are labelled as a PDT, you need to pay attention to the day trading buying power (DTBP) of your account. When the DTBP is insufficient, you will receive a DTCall. The server will intercept your order that exceeds the DTBP. If you still want to place the order and do not want the server to intercept it, you can take the following step:  
Via [Command Line OpenD](../opend/opend-cmd.html), modify the value of the startup parameter "dtcall_confirmation" to "0".  

![US_para2](../img/US_para2.png) 
NOTE: If the market value of a newly established position exceeds your remaining DTBP and you close the position in the same day, you will receive a DTCall, which can only be met by depositing funds.

### How to check my DTBP?
A:  
Via [Get Account Funds Interface](../trade/get-funds.html), you can request values related to day trading, such as Day Trades Left, Beginning DTBP, Remaining DTBP, etc.


## Q13: How to track the status of orders?
A:  
The two interfaces can be uesed to track the status of orders, after which have been placed.
<table>
    <tr>
      <th> Trading Enviroment </th>
      <th> Interfaces </th>
    </tr>
    <tr>
      <td > Real </td>
      <td > [Orders Push Callback](../trade/update-order.html), [Deals Push Callback](../trade/update-order-fill.html) </td>
    </tr>
    <tr>
	  <td> Simulate</td>
      <td> [Orders Push Callback](../trade/update-order.html)</td>
    </tr>
</table>

Note: Non-python users need to [Subscribe to Transaction Push](../trade/sub-acc-push.html) before using the above two interfaces.

#### Orders Push Callback:
Feedback changes of the entire order. The order push will be triggered when the following 8 fields change:  
`Order status`, `Order price`, `Order quantity`, `Deal quantity`, `Traget price`, `Trailing type`, `Trailing amount/ratio`, `Specify spread`  

Therefore, when you place, modify, cancel, enable, or disable the order, or when an advanced order is triggered or an order has transaction changes, it will cause orders push. You just need to call the [Orders Push Callback](../trade/update-order.html) to listen for these messages.

#### Deals Push Callback:
Feedback changes of a transaction. The order push will be triggered when the following field change:  
`Deal status`

Fot example: Suppose a limit order of 900 shares is divided into 3 transactions before it is completely filled, with each transaction being 200, 300 and 400 shares.
![example](../img/example.png)


## Q14: Why does the order interface return “The minimum tick size for this product is xxx. Please enter an integer multiple of the minimum tick size before submitting”?
A:   
Different exchanges have different rules on order price spreads. If the price of a submitted order does not follow relevant rules, the order will be rejected. 

### Rules on Price Spread
#### Hong Kong Market
Refer to the official [HKEX Spread Table](https://www.moomoo.com/us/support/topic4_304?from_platform=4)

#### China A-Shares
Stock price spread: 0.01

#### US Market
Stock Price Spreads: 
<table>
    <tr>
      <th> Price </th>
      <th> Spread </th>
    </tr>
    <tr>
      <td > Below $1 </td>
      <td > $0.0001 </td>
    </tr>
    <tr>
	  <td> $1 or above</td>
      <td> $0.01 </td>
    </tr>
</table>
Option Price Spreads:
<table>
    <tr>
      <th> Price </th>
      <th> Spread </th>
    </tr>
    <tr>
      <td > $0.10 - $3.00 </td>
      <td > $0.01 or $0.05 </td>
    </tr>
    <tr>
	  <td> $3.00+</td>
      <td> $0.05 or $0.10 </td>
    </tr>
</table>

Futures Price Spreads:   
Different contracts have different price spreads, which can be obtained via the `Price change step` of [Get Futures Contract Information](../quote/get-future-info.html) interface.

### How to ensure an order price meets spread rules?
* Method 1: Valid order prices can be obtained via the [Get Real-time Order Book](../quote/get-order-book.html) interface, since the prices of orders on the order book must be valid. 
* Method 2: Auto-adjust an order price to a valid value via the `Price adjustment range` parameter in the [Place Orders](../trade/place-order.html) interface.  

  How it works:  

  Suppose the Adjust Limit is set to 0.0015. A positive value means that OpenD will auto-adjust upward the price of a submitted order to a valid value within +0.15% of the original price. 
  
  Suppose the current market price of Tencent Holdings is 359.600, so the spread is 0.200 according to the HKEX Spread Table. Let’s say an order priced at 359.678 is submitted. In this case, the nearest upward valid price is 359.800, which means the order price only needs to be adjusted by 0.034%. The adjustment satisfies the Adjust Limit, so the final price of the submitted order is 359.800.  

  If the actual adjustment exceeds the Adjust Limit, OpenD will fail to auto-adjust the price, and the order submission will still return the error prompt "The minimum tick size for this product is xxx. Please enter an integer multiple of the minimum tick size before submitting".

## Q15: Why did it say "Insufficient Buying Power" when I place a market order with enough buying power in my account?
A:
### Why it indicates insufficient buying power when you place a market order
- For the sake of risk management, the system poses a higher buying power coefficient on market orders. With the same order parameters, a market order takes up more buying power than a limit order.
- Depending on different product types and market conditions, the risk management system dynamically adjusts the buying power coefficient of market orders. Therefore, when placing a market order, if you calculate the maximum buyable quantity using your maximum buying power, you are likely to get an inaccurate result.
### How to get the correct buyable quantity
Instead of calculating it, you can obtain the correct buyable quantity through the [Query the Maximum Quantity that Can be Bought or Sold] (../trade/get-max-trd-qtys.html) API.
 
### How to buy as much as possible
You can place a limit order at the BBO, instead of a market order.
In particular, the BBO means the best bid (or Bid 1) in the case of a sell order, or the best ask (or Ask 1) for a buy order.

## Q16: A brand-new API now supports US margin paper trading account
A:  
A brand-new API for paper trading now supports US margin paper trading account access and offers more comprehensive trading capabilities.    
The original API will gradually phase out paper trading services for US stocks. For a better experience, we recommend switching to the new API as soon as possible to enjoy enhanced US stock paper trading services.


## Q17: Instructions for Using Trade API Parameters
### 1. What is the Transaction Object?
Under your user ID, there is generally a margin universal account with several sub-accounts (usually two, a univeral securities account and a universal futures accoun; also a universal forex account if needed). Some users or instituational clients may open multiple universal accounts with multiple brokers.  
Creating a transaction object is the process of initially screening sub-accounts.  
- When calling get_acc_list using OpenSecTradeContext, only trading securities accounts will be returned.
- When calling get_acc_list using OpenFutureTradeContext, only trading futures accounts will be returned.  

The `security_firm` is used to filter accounts belonging to the corresponding securities firm, and the `filter_trdmarket` is used to filter accounts with the corresponding trading market permissions.

#### 1.1 security_firm
The brokers currently supported by Moomoo API are [as follows](../trade/trade.html#9434).

When calling get_acc_list, it will return the real account of the securities firm corresponding to security_firm and all paper trading accounts (paper trading has no concept of brokers, so no matter what security_firm is passed, all paper trading accounts will be returned).  
The default value of security_firm is FUTUSECURITIES. You can leave this parameter blank for FUTU HK accounts, but you need to modify this parameter when you want to obtain accounts from other brokers.  
* **Example 1**

```python
trd_ctx = OpenSecTradeContext(security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.get_acc_list()
print(data)
```
* **Output**
```python
               acc_id   trd_env acc_type      uni_card_num          card_num   security_firm sim_acc_type                  trdmarket_auth acc_status
0  281756478396547854      REAL   MARGIN  1001200163530138  1001369091153722  FUTUSECURITIES          N/A  [HK, US, HKCC, HKFUND, USFUND]     ACTIVE
1             3450309  SIMULATE     CASH               N/A               N/A             N/A        STOCK                            [HK]     ACTIVE
2             3548731  SIMULATE   MARGIN               N/A               N/A             N/A       OPTION                            [HK]     ACTIVE
3  281756455998014447      REAL   MARGIN               N/A  1001100320482767  FUTUSECURITIES          N/A                            [HK]   DISABLED
```

* **Example 2**
```python
trd_ctx = OpenSecTradeContext(security_firm=SecurityFirm.FUTUSG)
ret, data = trd_ctx.get_acc_list()
print(data)
```
* **Output**
```python
    acc_id   trd_env acc_type uni_card_num card_num security_firm sim_acc_type trdmarket_auth acc_status
0  3450309  SIMULATE     CASH          N/A      N/A           N/A        STOCK           [HK]     ACTIVE
1  3548731  SIMULATE   MARGIN          N/A      N/A           N/A       OPTION           [HK]     ACTIVE
```


#### 1.2 filter_trdmarket
The trading markets supported by Moomoo API are [as follows](../trade/trade.html#6257).

When calling get_acc_list, it will return all accounts with trading permissions in the filter_trdmarket market; when the filter_trdmarket is passed as NONE, the market will not be filtered and all accounts will be returned.  
The default trdmarket is HK. Under the universal account system, this parameter is used to filter paper trading accounts in different markets.  
* **Example 1**

```python
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US)
ret, data = trd_ctx.get_acc_list()
print(data)
```
* **Output**
```python
               acc_id   trd_env acc_type      uni_card_num          card_num   security_firm sim_acc_type                  trdmarket_auth acc_status
0  281756478396547854      REAL   MARGIN  1001200163530138  1001369091153722  FUTUSECURITIES          N/A  [HK, US, HKCC, HKFUND, USFUND]     ACTIVE
1             3450310  SIMULATE   MARGIN               N/A               N/A             N/A        STOCK                            [US]     ACTIVE
2             3548732  SIMULATE   MARGIN               N/A               N/A             N/A       OPTION                            [US]     ACTIVE
3  281756460292981743      REAL   MARGIN               N/A  1001100520714263  FUTUSECURITIES          N/A                            [US]   DISABLED
```

* **Example 2**
```python
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.NONE)
ret, data = trd_ctx.get_acc_list()
print(data)
```
* **Output**
```python
                acc_id   trd_env acc_type      uni_card_num          card_num   security_firm sim_acc_type                  trdmarket_auth acc_status
0   281756478396547854      REAL   MARGIN  1001200163530138  1001369091153722  FUTUSECURITIES          N/A  [HK, US, HKCC, HKFUND, USFUND]     ACTIVE
1              3450309  SIMULATE     CASH               N/A               N/A             N/A        STOCK                            [HK]     ACTIVE
2              3450310  SIMULATE   MARGIN               N/A               N/A             N/A        STOCK                            [US]     ACTIVE
3              3450311  SIMULATE     CASH               N/A               N/A             N/A        STOCK                            [CN]     ACTIVE
4              3548732  SIMULATE   MARGIN               N/A               N/A             N/A       OPTION                            [US]     ACTIVE
5              3548731  SIMULATE   MARGIN               N/A               N/A             N/A       OPTION                            [HK]     ACTIVE
6   281756455998014447      REAL   MARGIN               N/A  1001100320482767  FUTUSECURITIES          N/A                            [HK]   DISABLED
7   281756460292981743      REAL   MARGIN               N/A  1001100520714263  FUTUSECURITIES          N/A                            [US]   DISABLED
8   281756468882916335      REAL   MARGIN               N/A  1001100610464507  FUTUSECURITIES          N/A                          [HKCC]   DISABLED
9   281756507537621999      REAL     CASH               N/A  1001100910390035  FUTUSECURITIES          N/A                        [HKFUND]   DISABLED
10  281756550487294959      REAL     CASH               N/A  1001101010406844  FUTUSECURITIES          N/A                        [USFUND]   DISABLED
```
::: tip Tips  
When the filter_trdmarket is passed NONE, all trading accounts will be returned. Row 0 is the active real universal account, rows 1-5 are paper trading accounts, and rows 6-10 are disabled real accounts which are all single-market accounts, that have been replaced by the universal account (row 0). However, historical orders and deals are still in these disabled accounts, and you can query them via these accounts.  
There is no filter_trdmarket in the OpenFutureTradeContext, but security_firm, which has the same function as that in OpenSecTradeContext.  
:::  


### 2. Trade API Parameters 
When using specific trading API (such as place orders, get open orders), the `trd_env`, `acc_index`and `acc_id` parameters will first filter and confirm a unique account, and then implement the corresponding interface function for this account.  

![acc-select-en](../img/acc-select-en.png)

::: tip Summary
1. Filter out real or paper trading accounts according to trd_env.
2. Among the results, the account specified by acc_id is prioritized.
3. If acc_id is 0, select the corresponding account through acc_index.
4. Error: The specified acc_id does not exist, or the acc_index is out of range.  
:::


### 3. Examples
#### 3.1 Place Orders through Universal securities accounts
```python
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.NONE, security_firm=SecurityFirm.FUTUSECURITIES)
ret, data = trd_ctx.unlock_trade("123123")
if ret == RET_OK:
    print("unlock success!")
    ret, data = trd_ctx.place_order(45, 200, 'HK.00700', TrdSide.BUY,
                                    order_type=OrderType.NORMAL,
                                    trd_env=TrdEnv.REAL,
                                    acc_id=0)
    print(data)
```

#### 3.2 Get Open Orders through Universal futures accounts
```python
trd_ctx = OpenFutureTradeContext(security_firm=SecurityFirm.FUTUSECURITIES)

ret, data = trd_ctx.order_list_query(trd_env=TrdEnv.REAL,
                                     acc_id=0)
print(data)
```

#### 3.3 Get Account Funds through HK Cash Account (Paper Trading)
```python
# filter_trdmarket: TrdMarket.HK
# trd_env: TrdEnv.SIMULATE
# acc_index: 0
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.HK)
ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.SIMULATE, acc_index=0)
print(data)
```

#### 3.4 Trade Options through US Margin Account (Paper Trading)
```python
# Only two accounts returned after filtering by filter_trdmarket and trd_env
# acc_index = 0: US Cash Account (Trading stocks)
# acc_index = 1: US Margin Account (Trading options)
# acc_index: 1
trd_ctx = OpenSecTradeContext(filter_trdmarket=TrdMarket.US)
ret, data = trd_ctx.place_order(10, 1, code="US.AAPL250618P550000",trd_side=TrdSide.BUY,
                                trd_env=TrdEnv.SIMULATE,
                                acc_index=1)
print(data)
```

#### 3.5 Query the Max Quantity that can be Bought or Sold through JP Futures Paper Trading
```python
# Print the outcome of get_acc_list, the acc_id of JP Futures Paper Trading is 6271199
# Pass this acc_id when querying the max quantity that can be bought/sold
trd_ctx = OpenFutureTradeContext()
ret, data = trd_ctx.acctradinginfo_query(order_type=OrderType.NORMAL,
                                         price=5000,
                                         trd_env=TrdEnv.SIMULATE,
                                         acc_id=6271199,
                                         code="JP.NK225main")
print(data)
```


### 4. How to map the accounts in API to those in the APP?

![card-app-en](../img/card-app-en.png)  
The accounts on the APP only show the last 4-digits of the card number.   
According to the result of [get_acc_list](../trade/get-acc-list.html), the columns uni_card_num and card_num, are corresponding to the card number of Universal account and Single-market account (disabled), respectively.   
The account obtained in the API can be matched with that on the APP through the last 4 digits of the card number.

---

# Others

## Q1：How to build C++ API?

A:
moomoo-api c++ SDK is supported on Windows/MacOS/Linux. Pre-built libs are provided for the common build environment on each platform:
OS|Building Environment
:-|:-
Windows |Visual Studio 2013
Centos 7|g++ 4.8.5
Ubuntu 16.04|g++ 5.4.0
MacOS | XCode 11

If different compiler version is used, or different protobuf version is used, MMAPI and protobuf may be re-built. MMAPI source directory layout is:


```
MMAPI directory structure：
+---Bin                               Libs for common build environment
+---Include                           Public headers, source files generated from proto files
+---Sample                            Sample project
\---Src
    +---MMAPI                         MMAPI source
    +---protobuf-all-3.5.1.tar.gz     protobuf source
```

#### Build steps：
1. Build protobuf to generate libprotobuf static lib and protoc executable.
2. Generated C++ source files from proto files.
3. Build MMAPI to generate libMMAPI static lib

#### Step1: Build protobuf：
- Windows：
  - Install CMake
  - Open Visual Studio command prompt, change directory to protobuf/cmake
  - Run：cmake -G "Visual Studio 12 2013" -DCMAKE_INSTALL_PREFIX=install -Dprotobuf_BUILD_TESTS=OFF  This will generate Visual Studio 2013 solution file. Change -G parameter for other Visual Studio versions.
  - Open Visual Studio solution file, set platform toolset to v120_xp, then build.
- Linux (Refer to protobuf/src/README)
  - Run ./autogen.sh
  - Run CXXFLAGS="-std=gnu++11" ./configure --disable-shared
  - Run make
  - Put generated libprotobuf.a in Bin/Linux
- MacOS (Refer to protobuf/src/README)
  - Install dependencies with brew：autoconf automake libtool
  - Run ./configure CC=clang CXX="clang++ -std=gnu++11 -stdlib=libc++" --disable-shared

#### Step2: Generate C++ sources from proto files
- Use protoc to convert protofiles under Include/Proto to C++ source files. For example, the following command converts Common.proto to Common.pb.h and Common.pb.cc:
  - protoc -I="path-to-MMAPI/Include/Proto" --cpp_out="." path-to-MMAPI/Include/Proto/Common.proto
- Put the generated .h and .cc files in Include/Proto

#### Step3: Build MMAPI
- Windows：Create Visual Studio C++ static lib project，add source files under Src/MMAPI and Include，and set platform toolset to v120_xp.
- Mac：Create XCode C++ static lib project，add source files under Src/MMAPI and Include
- Linux：Use cmake to build MMAPI static lib, run following command under path-to-MMAPI/Src:
  - cmake -DTARGET_OS=Linux

## Q2: Is there more complete strategy examples for reference?

A:
* Python strategy examples are in the /moomoo/examples/ folder. You can find the path of Python API by executing the following command:
    ```
    import moomoo
    print(moomoo.__file__)
    ```
* The C# strategy examples are in the /MMAPI4NET/Sample/ folder
* The Java strategy examples are in the /MMAPI4J/sample/ folder
* The C++ strategy examples are under the /MMAPI4CPP/Sample/ folder
* The JavaScript strategy examples are in the /MMAPI4JS/sample/ folder

## Q3: Import error when using python API

**First Scene:**  
 I have already installed moomoo-api, but still get error: No module named 'moomoo'?  
It is possible that the interpreter your IDE currently uses is not the interpreter of the moomoo-api module you installed. In other words, your may have more than two Python environments installed on your computer.
You can do the following 2 steps:
1. Run the codes below to get the path of the current interpreter:
```
import sys
print(sys.executable)
```
Example diagram:   
 ![No module named 'moomoo'](../img/import-futu-error.png)

2. Run `$ D:\software\anaconda3\python.exe -m pip install moomoo-api` in command line (The first half of the command comes from the result of step 1).
This will install a moomoo-api module in the current interpreter.


## Q4: Import successful, but you still cannot call the relevant interface.

A: Usually in this case, you need to check if the ‘moomoo’ that was successfully imported is a correct moomoo API.

**First Scene:** There may be a file with the same name as 'moomoo'.
1. The current file name is moomoo.py
2. There is another file named moomoo.py under the path of the current file.
3. There is a folder named `/moomoo` under the path of the current file.

Therefore, we strongly recommend that you do not name files / folders / projects as *moomoo*.

**Second Scene:** A third-party library called 'moomoo' was installed by mistake.  

The correct name of the moomoo API library is `moomoo-api`, not 'moomoo'.

If you have installed a third-party library named 'moomoo', please uninstall it and [install moomoo-api](../quick/demo.md#6763).

Take PyCharm as an example: Check the installation of libraries.  

   ![settings](../img/settings.png)  
   ![futuku](../img/mmku.png)

   
## Q5: Protocol Encryption-Related

A:  
### Overview
To ensure privacy and confidentiality, you can use the asymmetric encryption algorithm RSA to encrypt the request and return between Strategy Scripts (moomoo API) and OpenD.  
If Strategy Scripts (moomoo API) is on the same computer as OpenD, it is usually not necessary to encrypt.

### Protocol Encryption Process
You can try to solve this problem with the following steps:
1. Generate the key file automatically through a third-party web platform.
    - To be specific: Search 'Online RSA Key Generator' on Baidu or Google. Set Key Format as PKCS#1. Set Key Length as 1024 bit. No password required. Then click the bottom 'Generate key pair'
    ![ui-config](../img/en_create_rsa.png)  
2. Copy and paste the private key into a text file. Save it to a specified path of the computer which OpenD is located in.
3. Specify the path of the RSA private key file on the computer which OpenD is located in. The path is the specified path mentioned in Step 2.
    - Method 1: Specify the path mentioned in Step 2 through 'Encryption Private Key' in [Visualization OpenD](../quick/opend-base.md#6196). As shown below:
    ![ui-config](../img/mmen_rsa_ui-config.png)
    - Method 2: Specify the path mentioned in Step 2 through the code `rsa_private_key` in [Command Line OpenD](../opend/opend-cmd.md#7893). As shown below:
    ![ui-config](../img/mm_xml.png)
4. Save the text file in step 2 to a specified path of the computer which Strategy Scripts (moomoo API) are located in, and [set the path of private key](../ftapi/init.md#6187) in Strategy Scripts.
5. Enable protocol encryption. There are two ways to enable protocol encryption.  
    - Method 1: Encrypt the context independently (general). You can set encryption through the parameter `is_encrypt` when creating and initializing the connection in [Quote Object](../quote/base.md#2335) or [Transaction Objects](../trade/base.md#8155).  
    - Method 2: Encrypt the context globally (only Python). You can set encryption through the interface [enable_proto_encrypt](../ftapi/init.md#7910).  


:::tip Tips
* When specifying the path of RSA private key in OpenD or in Strategy Scripts (moomoo API), the path needs to be complete and include the file name.
* It is not necessary to save RSA public key which can be calculated by private key.
:::


## Q6: Why is the DataFrame data I got incomplete?
A: When printing pandas.DataFrame data, if there are too many columns and rows, pandas will collapse the data by default, resulting in an incomplete display.  
Therefore, it is not OpenD's fault. You can add the following code in front of your Python script to solve the problem.
```
import pandas as pd
pd.options.display.max_rows=5000
pd.options.display.max_columns=5000
pd.options.display.width=1000
```

## Q7: How to solve the problem that "Cannot open libFTAPIChannel.dylib" through C++ API on Mac?

A: Execute the following command in the directory where the file "libFTAPIChannel.dylib" is stored: `$ xattr -r -d com.apple.quarantine libAPIChannel.dylib`.

## Q8: For Python users, why do large log files continue to be generated under the log folder, after the log level is set to no in the OpenD configuration file?
A：The *log_level* parameter in OpenD parameter configuration is only used to control the logs generated by OpenD. Python API also generates logs by default.   
If you do not like it, you can add the following codes to your Python script:
```
logger.file_level = logging.FATAL  # Used to stop Python API log files generating
logger.console_level = logging.FATAL  # Used to stop printing Python log in running console
```

## Q9: For versions 5.4 and above, the library name and configuration method of Java API have been changed.


A: 
* If you are a user of Java API 5.3 and below, please note the following changes when updating the version.  
**Changes to the configuration process:**


  1. Download moomoo API from [moomoo official website](https://www.moomoo.com/download).
  2. Decompress the downloaded file. `/MMAPI4J` is the directory of Java API. Add `/lib/moomoo-api-.x.y.z.jar` file to your project settings. To establish a moomoo-api project, please refer to [here](../quick/demo.html#1983). 


  **Changes to the directory:**
  1. For the Java version of moomoo API, the library name is changed from ftapi4j.jar to `moomoo-api-x.y.z.jar`, where "x.y.z" represents the version number.
  2. For the third-party library, the dependencies of /lib/jna.jar and /lib/jna-platform.jar are removed, and the dependencies of `/lib/bcprov-jdk15on-1.68.jar` and `/lib/bcpkix-jdk15on-1.68.jar` are added.
  ```
  +---mmapi4j                      MMAPI4J source code. If the JDK version used is not compatible, you can use the project to recompile the mmapi.jar.
  +---lib                          The folder with common libraries
  |    moomoo-api-x.y.z.jar          Java version of moomoo API
  |    bcprov-jdk15on-1.68.jar     Third-party library, for encryption and decryption
  |    bcpkix-jdk15on-1.68.jar     Third-party library, for encryption and decryption
  |    protobuf-java-3.5.1.jar     Third-party library, for parsing protobuf data
  +---sample                       Sample project
  +---resources                    The default generated directory of the maven project
  ```

* If you are a new user to the moomoo API, we provide a more convenient way to configure Java API via maven repository for you. About the configuration process, please refer to [here](../quick/demo.html#5062).


## Q10: For Python users, when using pyinstaller to package scripts that need to run api, an error is reported: Common_pb2 module cannot be found.

A: You can try to solve this problem with the following steps.  
Step 1. Suppose you need to package main.py. Using a command-line statement and run the statement: pyinstaller path\main.py, without the "- F" parameter. 
  ```
  pyinstaller path\main.py
  ```
After main.py is packaged, the /main folder will be created in the /dist directory where it is located. main.exe is in this folder.  
![dist](../img/mmdist.png)    

Step 2. Run the following code to find the installation path of moomoo-api: /path/moomoo.  
```
import moomoo
print(moomoo.__file__)
```  
Results:
  ```
  C:\Users\ceciliali\Anaconda3\lib\site-packages\moomoo\__init__.py
  ```
 ![pathfutu](../img/pathmoomoo.png)  
  
Step 3. Copy all the files in the /common/pb to /main.  

Step 4. Create a folder in the /main and name it moomoo. Copy the `/path/moomoo/VERSION.txt` file to /main/moomoo.     
 ![main_moomoo](../img/main_moomoo.png)   
Step 5. Try running the statement **pyinstaller main.py** again.


## Q11: Why the interface result is success, but the return did not behave as expected？
A:
* A successful interface result means that server has successfully received and responded to your request, but the return may not behave as your expected.

  Example: If you call the [subscribe](../quote/sub.md) during non-trading hours, your request can be responded successfully, but the exchange will not update the ticker data during this period. So you will temporarily not receive real-time data until trading hours.

* The interface result (definition: [Interface Result](../ftapi/common.md#8800)) can be viewed from the field returned. A field of 0 means the interface result success, a non-zero means the interface result failed.

  For python user, the following two code statements are equivalent:
  ```
  if ret_code == RET_OK:
  ```
  ```
  if ret_code == 0:
  ```

## Q12: WebSocket Related

### Overview
In Moomoo API, WebSocket is mainly used in the following two aspects:
* In Visualization OpenD, WebSocket is used to communicate between the UI interface and the underlying Command Line OpenD.
* The communication between JavaScript API and OpenD uses WebSocket.

![WebSocket-struct](../img/WebSocket-struct.png)  
* When WebSocket starts, Command Line OpenD establishes a Socket connection (TCP) with the **MMWebSocket transit service**. This connection uses the default **listening address** and **API protocol listening port**.
* At the same time, JavaScript API will establish a WebSocket connection (HTTP) with the **MMWebSocket transit service**. This connection will use the **WebSocket listening address** and **WebSocket port**.

### Usage
To ensure the security of your account, when WebSocket listens non-local requests, we strongly recommend that you enable SSL and configure the **WebSocket authentication key**

SSL is enabled by configuring the **WebSocket certificate** and the **WebSocket private key**.
Command Line OpenD can set the file path by configuring OpenD.xml or configuring command line parameters. Visualization OpenD clicks the "more" drop-down menu to see the confifuration item.

![ui-more-config](../img/mmui-more-config.png)

::: tip Tips
If the certificate is self-signed, you need to install the certificate on the machine where the JavaScript API is called, or set not to verify the certificate.
:::

#### Generate Self-signed Certificate
It is not convenient to expand the details of self-signed certificate generation in this document, please check it yourself.
Simple and available build steps are provided here:
1. Install openssl.
2. Modify openssl.cnf and add the IP address or domain name under the alt_names node on the machine where OpenD locates.  
For example: IP.2 = xxx.xxx.xxx.xxx, DNS.2 = www.xxx.com
3. Generate private key and certificate (PEM)。

**The certificate generation parameters are as follows**：  
`openssl req -x509 -newkey rsa:2048 -out moomoo.cer -outform PEM -keyout moomoo.key -days 10000 -verbose -config openssl.cnf -nodes -sha256 -subj "/CN=moomoo CA" -reqexts v3_req -extensions v3_req`

::: tip Tips
* openssl.cnf needs to be placed under the system path, or an absolute path needs to be specified in the build parameters.
* Note that while generating a private key, you need to specify that the password is not set (-notes).
:::

Attach the local self-signed certificate and the configuration file that generates the certificate for testing:  
* [openssl.cnf](../file/openssl.cnf)  
* [moomoo.cer](../file/cer)  
* [moomoo.key](../file/key)

## Q13: Where are the quote servers and the trade servers of API?
A：  
- Quote:

Futu ID|Quote Server Location
:-|:-|:-
Futubull ID|Tencent Cloud Guangzhou and Hong Kong
moomoo ID|Tencent Cloud Virginia, USA and Singapore

- Trade:  

Securities Firm|Trade Server Location
:-|:-|:-
FUTU HK|Tencent Cloud Hong Kong
Moomoo US|Tencent Cloud Virginia, USA
Moomoo SG|Tencent Cloud Singapore
Moomoo AU|Tencent Cloud Singapore
Moomoo MY|Ali Cloud Malaysia
Moomoo CA|AWS Cloud Canada
Moomoo JP|Tencent Cloud Japan

---

# Changelog

## 2026-06-25

### [OpenD 10.8.6808](https://www.moomoo.com/en/download/OpenAPI)

* [Search API](../quote/get-search-quote.md): Quickly find any asset by keyword.   
* [Search API](../quote/get-search-news.md): Find news, announcements, and ratings all in one place with one keyword.   
* [Chart Indicators](../quote/get-indicator-list.md): Supports all technical indicators in Mai Language and Python.  
* Comprehensive Options Analysis: IV/HV, Put/Call Ratio, 0DTE Options, Upcoming Earnings, and Seller Dashboard. See [Quote API](../quote/overview.md) for more details.   
* Market Fundamentals API: Access data from Institutional Tracker, Macroeconomic Data, Dividend & Earnings Calendars, Industry Chain, Market Movers, and Fed Rate Projections. See [Quote API](../quote/overview.md) for more details.


## 2026-06-04

### [OpenD 10.7.6708](https://www.moomoo.com/en/download/OpenAPI)

* Singapore (SG), Malaysia (MY), and Japan (JP) stocks market data now available — including real-time quotes, order book, K-line, fundamentals, and more. See [Quote Right](../intro/authority.md#2867) for details.   
* Supports trading for SG, MY, and JP stocks — order capabilities fully aligned with the App, covering users across HK / SG / MY / JP regions.  
* Supports market data and trading for options strategies, including straddle, spread, butterfly, and more. Pull market data via [Get Option Strategy](../quote/get-option-strategy.md), [Option P&L Analysis](../quote/get-option-strategy-analysis.md), and [Option Snapshot](../quote/get-option-quote.md); trade option strategies via [Place Combo Order](../trade/place-combo-order.md), and query buying-power changes via [Query Combo Order Buying Power](../trade/comboorder-tradinginfo-query.md).


## 2026-05-21

### [OpenD 10.6.6608](https://www.moomoo.com/en/download/OpenAPI)

* Combine screening conditions just like in the moomoo: call the [Stock Screeneing V2](../quote/get-stock-screen.md#8702) directly to freely combine filters across 5 dimensions (fundamentals, technicals, chart patterns), and screen for stocks matching your strategy in one line of code.
* Query individual stock fundamentals just like in the moomoo: call the [Get Financial Statements](../quote/get-financials-statements.md#8596) to retrieve the three major financial statements, revenue breakdown, analyst ratings, Morningstar reports, valuations (PE/PB/PS), dividends/buybacks/splits, shareholder holdings, insider trading, company profile & executives, top 10 brokers, and short-selling data.
* Moomoo Australia now supports paper trading competition accounts, with Skills-based account queries.


## 2026-05-07

### [OpenD 10.5.6508](https://www.moomoo.com/en/download/OpenAPI)

* Crypto market data and trading now available for users in HK, US, and SG.
* Query the account funds, positions, order history, and cash flows of Universal crypto account.
* New candlestick intervals [KLType](../quote/quote.md#4119):  `K_10M` (10-min), `K_120M` (2-hour), `K_180M` (3-hour), `K_240M` (4-hour).
* OpenD Skills now supports crypto features.


## 2026-04-23

### [OpenD 10.4.6408](https://www.moomoo.com/en/download/OpenAPI)

* The `security_firm` parameter in `OpenSecTradeContext()`, `OpenFutureTradeContext()`, and `OpenCryptoTradeContext()` now defaults to `NONE` — the system automatically detects the broker tied to your account, so you no longer need to specify it manually.
* New silent logging mode lets you suppress OpenD log output.
* Windows installer filenames now include the version number for easier identification.
* OpenD Skills performance improvements.


## 2026-04-16

### [OpenD 10.3.6308](https://www.moomoo.com/en/download/OpenAPI)

* US real-time market data now free during the promotional period.
* OpenD now allows login without a brokerage account — includes a complimentary quota of 100 real-time subscriptions and historical candlestick requests.
* Historical candlestick quota reset cycle shortened from 30 days to 7 days.


## 2026-03-26

### [OpenD 10.2.6208](https://www.moomoo.com/en/download/OpenAPI)

* US margin trading simulation now available via API — set `TrdEnv.SIMULATE` to place paper orders, with order status syncing to the moomoo in real time.
* OpenD Skills performance improvements.


## 2026-03-20

### OpenD 10.1.6108

* Introducing the all-new [Moomoo Skills Hub](https://www.moomoo.com/skillhub) — connect mainstream AI agents like OpenClaw, Claude Code, Cursor, and Codex.
* The [Moomoo API Skill](https://www.moomoo.com/skillhub/openapi) for market data & trading covers 56 endpoints across Hong Kong, US, China A-shares, Singapore, and Japan, with real-time quotes, smart trading, and live push capabilities.


## 2026-03-06

### OpenD 10.0.6018

* Moomoo API now available to users in Japan, Malaysia, and Canada.
* Bug fixes.


## 2025-12-17

### OpenD 9.6.5608

* Market data APIs now cover the Hang Seng index family, including 82 index symbols such as HK.800733 and HK.800734.
* [get_acc_list](../trade/get-acc-list.md#9665) now returns institutional master accounts (`TrdAccRole.MASTER`); note that master accounts are read-only and cannot place trades.
* Bug fixes.


## 2025-08-14

### OpenD 9.4.5408


* 24 Hour trading for US stocks — pass `Session.ALL` to [place_order()](../trade/place-order.md) to cover pre-market, regular, and after-hours sessions in a single order.
* Historical daily candlestick data now spans up to 20 years.
* US equities LV2 order book upgraded to 60 aggregated price levels; US futures LV2 upgraded to 40 levels.
* Adjusted price data now accounts for corporate spin-offs.
* The `min_change_unit` field in the [Get Futures Contract](../quote/get-future-info.md) API has been deprecated.