Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
jvQuant
https://jvquant.com/wiki
Admin
jvQuant是一个量化交易平台,提供市场行情数据(WebSocket、数据库)、数据查询、语义分析、历史数据下载以及交易接入等功能。
Tokens:
28,473
Snippets:
132
Trust Score:
5.3
Update:
9 months ago
Context
Chat
Benchmark
42
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### jvQuant Installation Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Instructions on how to install the jvQuant Python package. ```APIDOC ## Installation ### Description Instructions on how to install the jvQuant Python package. ### Requirements - Python version: Python >= 3 ### Commands ```bash pip install jvquant ``` Or ```bash python3 -m pip install jvquant ``` ``` -------------------------------- ### Java WebSocket Client Setup and Connection Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/SDK/Java%E6%8E%A5%E5%85%A5WebSocket%E8%A1%8C%E6%83%85 This snippet demonstrates the basic setup for a Java WebSocket client. It initializes the client with a WebSocket URL and establishes a connection. Ensure the server address and token are correctly configured. ```java package com.client; import java.net.URISyntaxException; public class Main { public static void main(String[] args) throws URISyntaxException { String wsUrl = "ws://<服务器地址>/?token=<jvQuant token>"; //分配服务器方法请参考:jvQuant.com/wiki/开始使用/分配服务器.html Client fd = new Client(wsUrl); fd.connect(); } } ``` -------------------------------- ### Install jvQuant Python Package Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Instructions for installing the jvQuant Python package using pip. This package requires Python version 3 or higher. ```bash pip install jvquant ``` ```bash python3 -m pip install jvquant ``` -------------------------------- ### Connect to CTP Counter Trading (Python) Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Example demonstrating how to connect to the CTP counter trading system using the jvQuant library. This enables functionalities like securities trading, position inquiries, order status checks, and order cancellations. It requires CTP account credentials and a platform authorization token. ```python import jvQuant import logging # 资金账号 ACCOUNT = "" # 资金密码 ACCOUNT_PWD = "" # 平台授权Token TOKEN = "" # 打印调试信息 LOG_LEVEL = logging.DEBUG # LOG_LEVEL = logging.INFO ctp = jvQuant.ctp_client ctpclient = ctp.Construct(token=TOKEN, ctp_acc=ACCOUNT, ctp_pwd=ACCOUNT_PWD, log_level=LOG_LEVEL) # 查询持仓信息 response = ctpclient.check_hold() # 查询委托状态 response = ctpclient.check_order() # 委托买入 response = ctpclient.buy("600519", "贵州茅台", "1572.12", "1000") # 委托卖出 response = ctpclient.sale("600519", "贵州茅台", "1572.12", "1000") # 撤销委托 response = ctpclient.cancel("9702") # 等待子线程结束 ctpclient.thread_join() ``` -------------------------------- ### Access Online Database Services (Python) Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Example demonstrating how to access various online database services using the jvQuant library. This includes intelligent semantic queries for financial and market data, retrieving industry classifications, bond information, historical minute and K-line data, and Level 2 order book and market depth data. Requires a platform authorization token. ```python import jvQuant import logging TOKEN = "" # 打印调试信息 LOG_LEVEL = logging.DEBUG # LOG_LEVEL = logging.INFO sql = jvQuant.sql_client sqlclient = sql.Construct(TOKEN, LOG_LEVEL) # 获取所有可转债基本信息 response = sqlclient.bond() # 获取所有证券的申万行业分类 response = sqlclient.industry() # Level2千档盘口查询 response = sqlclient.level_queue("600519") # Level2逐笔委托队列查询 response = sqlclient.order_book("000001", 0) # 最新队列 response = sqlclient.order_book("600519", 40676443) # 倒推查询 # 历史分时数据查询 response = sqlclient.minute("600519", '2016-06-21', 2) response = sqlclient.minute("i000001", '2009-06-21', 2) # 指数分时 # 智能语义查询 response = sqlclient.query("主板,非ST,价格,近5日涨幅,市盈率,市值大于20亿小于100亿,量比,营业额,利润率,利润,行业,股东人数,IPO时间", 1, 0, "INDUSTRY") response = sqlclient.query("集合竞价抢筹,30日均线向上,量比", 1, 1, "QRR") # K线查询 response = sqlclient.kline("600519", "stock", "前复权", "week", 2) response = sqlclient.kline("000001", "index", "后复权", "day", 2) response = sqlclient.kline("000001", "stock", "不复权", "day", 2) # 历史分时数据打包下载 # 遍历下载2008~2016年历史分时 for i in range(2008, 2016): sqlclient.download_history(str(i)) # 指定年份下载 sqlclient.download_history("2024") sqlclient.download_history("2025") ``` -------------------------------- ### Connect to A-Share WebSocket Market Data (Python) Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Example demonstrating how to connect to A-share market data via WebSocket using the jvQuant library. It supports Level 1, Level 2, and 10-level market data subscriptions for various securities. Custom handlers for logging, raw data, and different market data levels can be registered. ```python import jvQuant import logging '''沪深行情订阅示例''' # 自定义日志处理函数 def logHandle(log: str): print("应用日志:", log) # 自定义原始行情处理函数 def dataHandle(data: str): print("Binary解析结果:", data) # 自定义level1行情处理函数 def ab_lv1_handle(lv1: jvQuant.websocket_client.parse.AbLv1): print("level1推送:", lv1.get_map()) # 自定义level2行情处理函数 def ab_lv2_handle(lv2: jvQuant.websocket_client.parse.AbLv2): print("level2推送:", lv2.get_map()) # 自定义十档行情处理函数 def ab_lv10_handle(lv10: jvQuant.websocket_client.parse.AbLv10): print("十档推送:", lv10.get_map()) # 沪深市场标志 market = "ab" # 平台授权Token token = "" # 打印调试信息 log_level = logging.DEBUG # log_level = logging.INFO ws = jvQuant.websocket_client # 注册自定义行情处理函数 wsclient = ws.Construct(market=market, token=token, log_level=log_level, log_handle=logHandle, data_handle=dataHandle, ab_lv1_handle=ab_lv1_handle, ab_lv2_handle=ab_lv2_handle, ab_lv10_handle=ab_lv10_handle) # 发送订阅代码 wsclient.add_lv1(["600519", "000001", "i000001"]) wsclient.add_lv2(["600519", "000001", "i000001"]) wsclient.add_lv10(["600519", "000001", "i000001"]) # 等待子线程结束 wsclient.thread_join() ``` -------------------------------- ### Basic Market Data (lv1) Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%A7%A3%E6%9E%90/%E6%B8%AF%E8%82%A1%E8%A1%8C%E6%83%85%E8%A7%A3%E6%9E%90 Parses the decompressed WebSocket data for basic Hong Kong stock market information. Data is delimited by newlines, with each line starting with a market flag and stock code. ```APIDOC ## Basic Market Data (lv1) ### Description Parses the decompressed WebSocket data for basic Hong Kong stock market information. Data is delimited by newlines, with each line starting with a market flag and stock code. ### Method WebSocket Push ### Endpoint N/A (WebSocket Stream) ### Parameters N/A ### Request Example N/A ### Response #### Data Format `lv1_证券代码1=推送时间,证券名称(英),证券名称(中),最新价格,涨幅,成交额,成交量,买十档[挂单数量,挂单价格,...],卖十档[挂单数量,挂单价格,...]` `lv1_证券代码2=推送时间,证券名称(英),证券名称(中),最新价格,涨幅,成交额,成交量,买十档[挂单数量,挂单价格,...],卖十档[挂单数量,挂单价格,...]` **Field Descriptions:** - `lv1`: Indicates basic market data level. - `证券代码`: Unique identifier for the stock. - `推送时间`: Timestamp of the data update. - `证券名称(英)`: English name of the stock. - `证券名称(中)`: Chinese name of the stock. - `最新价格`: Current trading price. - `涨幅`: Current price change percentage. - `成交额`: Total transaction value. - `成交量`: Total transaction volume. - `买十档`: Top ten bid orders (quantity, price). - `卖十档`: Top ten ask orders (quantity, price). #### Response Example ``` lv1_0001.HK=2023-10-27 10:30:00,TENCENT,腾讯控股,300.00,+1.50,150000000,500000,[100,299.50,200,299.00,...],[150,300.50,250,301.00,...] lv1_0700.HK=2023-10-27 10:30:00,SAMSUNG,三星电子,75000.00,-0.80,750000000,100000,[50,74900.00,100,74800.00,...],[75,75100.00,120,75200.00,...] ``` ``` -------------------------------- ### PHP WebSocket Market Data Subscription Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/SDK/PHP%E6%8E%A5%E5%85%A5WebSocket%E8%A1%8C%E6%83%85 This PHP script connects to a WebSocket server using Swoole to subscribe to market data. It requires the Swoole extension to be installed. The script sends a subscription message and then enters a loop to receive and process incoming data, decompressing it if necessary. It takes server address, port, and a jvQuant token as input. ```php <?php //需安装swoole扩展 use Swoole\Coroutine\Http\Client; use function Swoole\Coroutine\run; run(function () { //服务器地址 $host = '<服务器地址>'; //服务器端口 $port = <服务器端口>; //分配服务器方法请参考:jvQuant.com/wiki/开始使用/分配服务器.html //连接 $conn = new Client($host, $port); $conn->upgrade("/?token=<jvQuant token>"); //发送订阅 $conn->push("add=lv2_600519,lv1_000001"); //开启接收协程 go("receive", $conn); }); function receive($client) { while (true) { $data = $client->recv(); $time = date("H:i:s"); //解压缩 @$zipStr = gzinflate($data->data); if ($zipStr) { echo "{$time} Binary推送:{$zipStr}\n"; } else { echo "{$time} Text响应:{$data->data}\n"; } } } ?> ``` -------------------------------- ### Hong Kong Stock Market Data Subscription Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%AE%A2%E9%98%85/%E6%B8%AF%E8%82%A1%E8%A1%8C%E6%83%85%E8%AE%A2%E9%98%85 This section details how to subscribe to Hong Kong stock market data via WebSocket. It covers the format of subscription codes, the available commands for managing subscriptions, and examples of their usage. ```APIDOC ## Hong Kong Stock Market Data Subscription API ### Description This API enables real-time subscription to Hong Kong stock market data, including Level 1 (basic) and Level 2 (tick-by-tick) data for approximately 5000 securities such as main board stocks, warrants, and ETFs. ### Method WebSocket ### Endpoint `wss://your-websocket-endpoint.com` (Example endpoint, actual endpoint may vary) ### Parameters #### Subscription Code Format Subscription codes are formed by combining a market data type indicator with a security code, separated by an underscore (`_`). - **Market Data Types:** - `lv1`: Basic market data (Level 1) - `lv2`: Tick-by-tick transaction data (Level 2) - **Security Code:** The unique code for the stock, warrant, or ETF (e.g., `00700`). - **Examples:** - `lv1_00700`: Subscribe to basic market data for security `00700`. - `lv2_00700`: Subscribe to tick-by-tick transaction data for security `00700`. #### Subscription Management Commands After successfully connecting to the WebSocket server, clients can use the following commands to manage their subscriptions. Commands are sent as text messages to the server. - **`add`**: Add one or more subscription codes. - **Format:** `add=<code>1</code>,<code>2</code>,...` - **Example:** `add=lv1_00700,lv2_00700` - **`del`**: Delete one or more subscription codes. - **Format:** `del=<code>1</code>,<code>2</code>,...` - **Example:** `del=lv1_00700,lv2_00700` - **`all`**: Set all subscription codes, replacing the current list. - **Format:** `all=<code>1</code>,<code>2</code>,...` - **Example (subscribe to only 00700 basic data):** `all=lv1_00700` - **Example (clear all subscriptions):** `all=` - **`list`**: View the currently subscribed information for the active connection. - **Format:** `list` - **Example:** `list` - **`his`**: View the account's subscribed information for the current day. - **Format:** `his` - **Example:** `his` **Note:** Multiple subscription codes within a command (for `add`, `del`, `all`) should be separated by commas (`,`). ### Request Example ``` add=lv1_00700,lv2_00700 ``` ### Response Responses from the server will typically be in a structured format (e.g., JSON) detailing the market data or the status of subscription management commands. Specific response formats for data pushes are not detailed here but would include the subscribed data points. #### Success Response Examples - **For `list` command:** ```json { "subscribed": [ "lv1_00700", "lv2_00700" ] } ``` - **For `add` command (confirmation):** ```json { "status": "success", "message": "Subscriptions added successfully." } ``` #### Error Handling - Invalid command format. - Invalid subscription code. - Connection errors. - Rate limiting (if applicable). ### Online Testing An online testing tool is available at: [港股WebSocket实时行情在线测试](link-to-online-tester) ``` -------------------------------- ### Connect and Subscribe to WebSocket Market Data in Golang Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/SDK/Golang%E6%8E%A5%E5%85%A5WebSocket%E8%A1%8C%E6%83%85 This Go code snippet demonstrates how to establish a WebSocket connection to a market data server, send a subscription command for specific instruments, and continuously receive data. It includes logic for handling text messages and decompressing binary messages using flate. Dependencies include the 'gorilla/websocket' library. ```go package main import ( "bytes" "compress/flate" "github.com/gorilla/websocket" "log" "time" ) func main() { //连接地址 wsUrl := "ws://<服务器地址>/?token=<jvQuant token>" //分配服务器方法请参考:jvQuant.com/wiki/开始使用/分配服务器.html conn, _, err := websocket.DefaultDialer.Dial(wsUrl, nil) if err != nil { log.Fatalln("连接错误:", err) } //接收协程 go func() { receive(conn) }() //发送订阅 cmd := "all=lv2_600519,lv1_000001" err = conn.WriteMessage(websocket.TextMessage, []byte(cmd)) if err != nil { log.Fatalln("发送指令错误:", err) } log.Println("发送指令成功,等待接收") for { time.Sleep(time.Second) } } func receive(conn *websocket.Conn) { for { //阻塞接收 messageType, rb, err := conn.ReadMessage() if err != nil { log.Fatalln("接收错误:", err) return } //文本消息 if messageType == websocket.TextMessage { log.Println("Text响应:", string(rb)) } //二进制消息 if messageType == websocket.BinaryMessage { unZipByte := DeCompress(rb) log.Println("Binary推送:", string(unZipByte)) } } } //解压缩方法 func DeCompress(b []byte) []byte { var buffer bytes.Buffer buffer.Write([]byte(b)) reader := flate.NewReader(&buffer) var result bytes.Buffer result.ReadFrom(reader) reader.Close() return result.Bytes() } ``` -------------------------------- ### Get All Stocks List Source: https://jvquant.com/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93/%E8%82%A1%E7%A5%A8%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF%E6%9F%A5%E8%AF%A2 Retrieves a list of all stocks in the Shanghai and Shenzhen markets. Requires a database server and authentication token. ```APIDOC ## GET /sql ### Description Retrieves a list of all stocks in the Shanghai and Shenzhen markets. This endpoint requires a database server and a valid authentication token. ### Method GET ### Endpoint `http://<database_server>/sql` ### Query Parameters - **mode** (string) - Required - Query category. Use `industry` for stock basic information. - **token** (string) - Required - User account authentication token for verifying request permissions. ### Response #### Success Response (200) - **count** (int) - The total number of stocks in the market. - **fields** ([]string) - An array of strings defining the data fields available for each stock. - **list** ([]string) - An array of arrays, where each inner array represents a stock and its details. #### Response Example ```json { "code": 0, "cnt": 1, "msg": "", "data": { "count": 5210, "fields": [ "股票代码", "股票简称", "所属行业", "流通股数" ], "list": [ [ "000001", "平安银行", "银行", "19405617528" ], ... [ "689009", "九号公司-WD", "交运设备", "546389844" ] ] } } ``` ``` -------------------------------- ### Stock List Query Response Example Source: https://jvquant.com/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93/%E8%82%A1%E7%A5%A8%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF%E6%9F%A5%E8%AF%A2 This JSON structure represents the successful response when querying the stock list. It includes the total count of stocks, definitions of the data fields, and a list containing the stock data itself, with each inner list representing a single stock's details. ```json { "code": 0, "cnt": 1, "msg": "", "data": { "count": 5210, "fields": [ "股票代码", "股票简称", "所属行业", "流通股数" ], "list": [ [ "000001", "平安银行", "银行", "19405617528" ], ... [ "689009", "九号公司-WD", "交运设备", "546389844" ] ] } } ``` -------------------------------- ### C++ WebSocket Client for Market Data Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/SDK/C%2B%2B%E6%8E%A5%E5%85%A5WebSocket%E8%A1%8C%E6%83%85 This C++ code snippet demonstrates how to establish a WebSocket connection to a market data feed using the websocketpp library. It includes handlers for connection opening and message reception, as well as a function to decompress binary data received from the server. ```cpp #include <websocketpp/config/asio_no_tls_client.hpp> #include <websocketpp/client.hpp> #include <string> #include <iostream> #include <memory> #include <assert.h> #include <cstring> #include "zlib.h" #define CHUNK 16384 using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; typedef websocketpp::client <websocketpp::config::asio_client> client; typedef websocketpp::config::asio_client::message_type::ptr message_ptr; int DecompressString(const char *in_str, size_t in_len, std::string &out_str); /** * 接收处理 */ void on_message(client *c, websocketpp::connection_hdl hdl, message_ptr msg) { //文本消息 if (msg->get_opcode()==websocketpp::frame::opcode::text){ std::cout <<"Text响应:"<<msg->get_payload().c_str()<< std::endl; } //二进制消息 if (msg->get_opcode()==websocketpp::frame::opcode::binary){ std::string tmp = ""; std::string &out_decompress = tmp; DecompressString( msg->get_payload().c_str(), msg->get_payload().size(), out_decompress); std::cout <<"Binary响应:"<<out_decompress<< std::endl; } } /** * 连接处理 */ void on_open(client *c, websocketpp::connection_hdl hdl) { //发送订阅指令 c->send(hdl, "add=lv1_600519,lv2_600519", websocketpp::frame::opcode::text); std::cout << "连接成功" << std::endl; } int main(int argc, char *argv[]) { //服务地址。 注意:C++版本的地址 问号前需加斜杠 std::string wsUrl = "ws://<服务器地址>/?token=<jvQuant token>"; //分配服务器方法请参考:jvQuant.com/wiki/开始使用/分配服务器.html client c; //连接相关 try { //输出debug日志 c.clear_access_channels(websocketpp::log::alevel::all); c.init_asio(); // 注册处理函数 c.set_message_handler(bind(&on_message, &c, ::_1, ::_2)); c.set_open_handler(bind(&on_open, &c, _1)); websocketpp::lib::error_code ec; client::connection_ptr con = c.get_connection(wsUrl, ec); if (ec) { std::cout << "连接失败: " << ec.message() << std::endl; return 0; } c.connect(con); c.run(); } catch (websocketpp::exception const &e) { std::cout << e.what() << std::endl; } } /** *解压缩方法 */ int DecompressString(const char *in_str, size_t in_len, std::string &out_str) { if (!in_str) return Z_DATA_ERROR; int ret; unsigned have; z_stream strm; unsigned char out[CHUNK]; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit2(&strm, -MAX_WBITS); if (ret != Z_OK) return ret; std::shared_ptr <z_stream> sp_strm(&strm, [](z_stream *strm) { (void) inflateEnd(strm); }); const char *end = in_str + in_len; size_t pos_index = 0; size_t distance = 0; int flush = 0; do { distance = end - in_str; strm.avail_in = (distance >= CHUNK) ? CHUNK : distance; strm.next_in = (Bytef *) in_str; in_str += strm.avail_in; flush = (in_str == end) ? Z_FINISH : Z_NO_FLUSH; do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR) break; switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: return ret; } have = CHUNK - strm.avail_out; out_str.append((const char *) out, have); } while (strm.avail_out == 0); } while (flush != Z_FINISH); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } ``` -------------------------------- ### WebSocket 行情订阅 Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%AE%A2%E9%98%85/%E6%B2%AA%E6%B7%B1%E8%A1%8C%E6%83%85%E8%AE%A2%E9%98%85 通过WebSocket连接订阅沪深股市的实时行情数据。支持添加、删除、设置全部订阅代码,以及查看当前和历史订阅信息。 ```APIDOC ## WebSocket 行情订阅 ### Description 通过WebSocket连接订阅沪深股市的实时行情数据。支持添加、删除、设置全部订阅代码,以及查看当前和历史订阅信息。 ### Method WebSocket ### Endpoint `wss://your-websocket-endpoint.com` ### Parameters #### Query Parameters - **指令** (string) - Required - 用于控制行情订阅操作,可选值包括 `add`, `del`, `all`, `list`, `his`。 - `add`: 增加订阅代码。格式: `add=lv1_000001,lv2_000001,lv10_000001,... - `del`: 删除订阅代码。格式: `del=lv1_000001,lv2_000001,lv10_000001,... - `all`: 设置全部订阅代码。格式: `all=lv1_000001,lv2_000001,lv10_000001,...` 或 `all=` (清空全部订阅)。 - `list`: 查看当前连接已订阅信息。无需参数。 - `his`: 查看账户今日已订阅信息。无需参数。 #### Request Body ### Request Example ``` add=lv1_600519,lv2_127063 del=lv1_600519,lv2_127063 all=lv1_600519 all= list his ``` ### Response #### Success Response (200) - **订阅数据** (string) - 实时行情数据推送,格式根据订阅类别而定。 - **确认信息** (string) - 操作指令的执行结果确认。 #### Response Example ```json { "type": "trade", "symbol": "000001.SZ", "price": 10.50, "volume": 100 } ``` ### Error Handling - **连接错误**: WebSocket连接失败。 - **指令错误**: 提供的指令或订阅代码格式不正确。 - **权限错误**: 无权访问该行情数据。 ``` -------------------------------- ### Query Server Allocation Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/%E5%88%86%E9%85%8D%E6%9C%8D%E5%8A%A1%E5%99%A8 This endpoint allows you to query and obtain a server allocation for a specific market and business type. It is recommended to query for a new server address before each connection as allocations may change. ```APIDOC ## GET /query/server ### Description Queries and allocates a business server based on the specified market, business type, and authentication token. It's crucial to re-query before each connection as server assignments can change. ### Method GET ### Endpoint `/query/server` ### Parameters #### Query Parameters - **market** (string) - Required - The market identifier (e.g., 'ab' for Shanghai/Shenzhen, 'hk' for Hong Kong, 'us' for US markets). - **type** (string) - Required - The business type identifier (e.g., 'websocket' for real-time quotes, 'sql' for database services, 'trade' for trading services). - **token** (string) - Required - Your account token for authentication. ### Request Example ```json { "example": "http://jvQuant.com/query/server?market=ab&type=websocket&token=<YourToken>" } ``` ### Response #### Success Response (200) - **code** (string) - Indicates the request status. '0' signifies success. - **server** (string) - The allocated business server address. #### Response Example ```json { "code": "0", "server": "<business_server_address>" } ``` ``` -------------------------------- ### 千档盘口查询 Source: https://jvquant.com/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93/%E6%B2%AA%E6%B7%B1Level2%E5%8D%83%E6%A1%A3%E7%9B%98%E5%8F%A3%E9%98%9F%E5%88%97%E6%9F%A5%E8%AF%A2 此API用于查询指定股票代码的千档盘口数据。需要提供数据库服务器地址、股票代码和jvQuant账户Token。 ```APIDOC ## GET /sql ### Description 查询千档盘口数据,包括买卖档位、价格、挂单总量、挂单笔数和队列。 ### Method GET ### Endpoint `http://<数据库服务器>/sql` ### Query Parameters - **mode** (string) - Required - 查询类别,千档盘口查询使用`level_queue` - **code** (string) - Required - 需要查询的证券代码 - **token** (string) - Required - jvQuant账户Token,用于验证请求权限 ### Request Example ``` http://<数据库服务器>/sql?mode=level_queue&code=000001&token=<token> ``` ### Response #### Success Response (200) - **code** (integer) - 响应码,0表示成功。 - **cnt** (integer) - 返回记录数。 - **msg** (string) - 响应消息。 - **data** (object) - 包含盘口详细信息的对象。 - **code** (string) - 证券代码。 - **count** (integer) - 总档位数。 - **fields** (array) - 档位类别列表,例如["S100", "S99", ..., "B99", "B100"]。 - **list** (array) - 档位详细信息列表。 - **type** (string) - 档位类别,`买N`或`卖N`,`B`表示买,`S`表示卖。 - **price** (float) - 档位价格。 - **volume_count** (integer) - 档位挂单总量(股)。 - **queue_count** (integer) - 档位挂单笔数。 - **queue_slice** (string) - 档位挂单队列,以逗号分隔的挂单量列表。 #### Response Example ```json { "code": 0, "cnt": 1, "msg": "", "data": { "code": "000001", "count": 143, "fields": ["S100", "S99", ..., "B99", "B100"], "list": [ { "type": "S100", "price": 12.53, "volume_count": 3250700, "queue_count": 386, "queue_slice": "5500,600,15000,200,3500,1000,300,800..." }, ... { "type": "B100", "price": 12.5, "volume_count": 98100, "queue_count": 28, "queue_slice": "1300,1000,4900,6200,1800,1000,2000,30000..." } ] } } ``` ``` -------------------------------- ### Online Testing Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%A7%A3%E6%9E%90/%E6%B8%AF%E8%82%A1%E8%A1%8C%E6%83%85%E8%A7%A3%E6%9E%90 Provides a link for online testing of Hong Kong real-time market data interfaces. ```APIDOC ## Online Testing ### Description Provides a link for online testing of Hong Kong real-time market data interfaces. ### Method Web Link ### Endpoint [港股实时行情接口在线测试](https://example.com/hk-market-test) (Note: Replace with actual URL if available) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### WebSocket Market Data Server Connection Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%BF%9E%E6%8E%A5WebSocket Connect to the WebSocket market data server using the provided address and account token. ```APIDOC ## POST /ws ### Description Connect to the WebSocket market data server. ### Method GET ### Endpoint `ws://<market_server_address>?token=<account_token>` ### Parameters #### Query Parameters - **market_server_address** (string) - Required - The address of the market data server. - **account_token** (string) - Required - The authentication token for the account. ### Request Example ``` ws://your_market_server_address.com?token=your_account_token ``` ### Response #### Success Response (101 Switching Protocols) - **Connection established** - The WebSocket connection is successfully established. #### Response Example (No specific response body for a successful WebSocket handshake, typically just the status code 101) ``` -------------------------------- ### WebSocket - 美股逐笔成交 Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%A7%A3%E6%9E%90/%E7%BE%8E%E8%82%A1%E8%A1%8C%E6%83%85%E8%A7%A3%E6%9E%90 通过WebSocket接收美股逐笔成交数据。数据经过压缩和编码,需先解压缩和解析。 ```APIDOC ## WebSocket /subscribe/marketdata/us/tick ### Description Subscribes to real-time US stock tick-by-tick transaction data via WebSocket. Data is compressed and encoded, requiring decompression and parsing on the client side. ### Method WEBSOCKET ### Endpoint `/subscribe/marketdata/us/tick` ### Parameters None (Connection established via WebSocket handshake) ### Data Format (after decompression and parsing) Multiple transactions within the same time period are delimited by `|`. Fields within each transaction are separated by `,`. **Format:** ``` <level>_<security_code>=<trade_time1>,<session_type1>,<trade_id1>,<price1>,<volume1>...|<trade_time2>,<session_type2>,<trade_id2>,<price2>,<volume2>... ``` - `level`: Indicates the market data level (e.g., `lv2` for tick-by-tick data). - `security_code`: Unique identifier for the stock. - `trade_time`: The specific time of the transaction. - `session_type`: Indicates the trading session: `PRE` (Pre-market), `RTH` (Regular Trading Hours), `AFT` (After-hours). - `trade_id`: Unique identifier for the transaction. - `price`: The transaction price. - `volume`: The transaction volume. ### US Session Type Mapping | Symbol | Description | |---|---| | PRE | Pre-market trading | | RTH | Regular trading hours | | AFT | After-hours trading | ### Response Example (per message) ``` "lv2_AAPL=10:00:05,RTH,12345,170.50,100|10:00:06,RTH,12346,170.55,50" "lv2_GOOG=10:00:07,RTH,12347,135.20,200|10:00:08,RTH,12348,135.15,150" ``` ``` -------------------------------- ### WebSocket - 美股基础行情 Source: https://jvquant.com/wiki/%E8%A1%8C%E6%83%85/%E8%A7%A3%E6%9E%90/%E7%BE%8E%E8%82%A1%E8%A1%8C%E6%83%85%E8%A7%A3%E6%9E%90 通过WebSocket接收美股基础行情数据。数据经过压缩和编码,需先解压缩和解析。 ```APIDOC ## WebSocket /subscribe/marketdata/us/level1 ### Description Subscribes to real-time US stock basic market data via WebSocket. Data is compressed and encoded, requiring decompression and parsing on the client side. ### Method WEBSOCKET ### Endpoint `/subscribe/marketdata/us/level1` ### Parameters None (Connection established via WebSocket handshake) ### Data Format (after decompression and parsing) Data is delimited by newline characters (`\n`). Each line starts with a market data flag and a security code. **Format:** ``` <level>_<security_code>=<us_symbol>,<last_price>,<change_percent>,<turnover_value>,<volume>,<timestamp>... ``` - `level`: Indicates the market data level (e.g., `lv1` for basic market data). - `security_code`: Unique identifier for the stock. - `us_symbol`: The stock's symbol in the US market. - `last_price`: The current trading price of the stock. - `change_percent`: The percentage change in price. - `turnover_value`: Total trading value. - `volume`: Total trading volume. - `timestamp`: The time of data update. ### Response Example (per message) ``` "lv1_AAPL=AAPL,170.50,1.25,25000000,150000,2023-10-27T10:00:00Z" "lv1_GOOG=GOOG,135.20,-0.50,18000000,130000,2023-10-27T10:00:01Z" ``` ``` -------------------------------- ### 查询交易 Source: https://jvquant.com/wiki/%E5%88%B8%E5%95%86%E4%BA%A4%E6%98%93%E6%8E%A5%E5%8F%A3/%E6%9F%A5%E8%AF%A2%E4%BA%A4%E6%98%93 此API用于查询用户的交易记录。您可以通过提供认证Token和交易凭证来获取交易列表。 ```APIDOC ## GET /check_order ### Description 查询用户的交易记录,返回交易列表详情。 ### Method GET ### Endpoint `http://<柜台地址>/check_order` ### Parameters #### Query Parameters - **token** (string) - Required - 用户账户的认证token,用于验证请求权限。 - **ticket** (string) - Required - 交易凭证 ### Response #### Success Response (200) - **code** (string) - 响应码,通常为 "0" 表示成功。 - **message** (string) - 错误信息,成功时为空。 - **list** (array) - 交易记录列表。 - **order_id** (string) - 委托编号 - **day** (string) - 委托日期 - **time** (string) - 委托时间 - **code** (string) - 证券代码 - **name** (string) - 证券名称 - **type** (string) - 委托类型 - **status** (string) - 委托状态 - **order_price** (string) - 委托价格 - **order_volume** (string) - 委托数量 - **deal_price** (string) - 成交价格 - **deal_volume** (string) - 成交数量 #### Response Example ```json { "code": "0", "message": "", "list": [ { "order_id": "1334564", "day": "20180402", "time": "142423", "code": "110074", "name": "精达转债", "type": "证券卖出", "status": "已成", "order_price": "151.885", "order_volume": "8000", "deal_price": "151.927", "deal_volume": "8000" } ] } ``` ``` -------------------------------- ### 交易委托 (Order Submission) Source: https://jvquant.com/wiki/%E5%88%B8%E5%95%86%E4%BA%A4%E6%98%93%E6%8E%A5%E5%8F%A3/%E5%88%B8%E5%95%86%E4%BA%A4%E6%98%93%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8 Submit a trading order with specified details. ```APIDOC ## POST /websites/jvquant_wiki/order ### Description Submits a trading order with the provided details. ### Method POST ### Endpoint http://<柜台地址>/<type>?&token=<token>&ticket=<交易凭证>&code=<证券代码>&name=<证券名称>&price=<委托价格>&volume=<委托数量> ### Parameters #### Query Parameters - **type** (string) - Required - Order type, 'buy' for buy, 'sale' for sell. - **token** (string) - Required - Authentication token for the user account, used to verify request permissions. - **ticket** (string) - Required - Trading voucher. - **code** (string) - Required - Security code. - **name** (string) - Required - Security name. - **price** (string) - Required - Order price. - **volume** (string) - Required - Order volume. ### Request Example ```json { "example": "http://<柜台地址>/buy?&token=<token>&ticket=<交易凭证>&code=000001.SZ&name=平安银行&price=10.50&volume=100" } ``` ### Response #### Success Response (200) - **code** (string) - Response code, '0' indicates success. - **message** (string) - Response message, empty if successful. - **order_id** (string) - The ID of the submitted order. #### Response Example ```json { "code": "0", "message": "", "order_id": "<委托编号>" } ``` ``` -------------------------------- ### CTP Counter Trading Source: https://jvquant.com/wiki/%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/pip%E7%A4%BA%E4%BE%8B Full implementation of broker counter functions, including securities trading, position inquiry, transaction inquiry, and order cancellation. ```APIDOC ## CTP Counter Trading ### Description Full implementation of broker counter functions, including securities trading, position inquiry, transaction inquiry, and order cancellation. ### Method ```python import jvQuant import logging # Account credentials ACCOUNT = "" ACCOUNT_PWD = "" # Platform authorization token TOKEN = "" # Log level for debugging information LOG_LEVEL = logging.DEBUG ctp = jvQuant.ctp_client ctpclient = ctp.Construct(token=TOKEN, ctp_acc=ACCOUNT, ctp_pwd=ACCOUNT_PWD, log_level=LOG_LEVEL) # Query current positions response = ctpclient.check_hold() # Query order status response = ctpclient.check_order() # Place a buy order response = ctpclient.buy("600519", "贵州茅台", "1572.12", "1000") # Place a sell order response = ctpclient.sale("600519", "贵州茅台", "1572.12", "1000") # Cancel an existing order response = ctpclient.cancel("9702") # Wait for the background thread to finish ctpclient.thread_join() ``` ``` -------------------------------- ### Download Historical Market Data Source: https://jvquant.com/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93/%E6%B2%AA%E6%B7%B1%E8%82%A1%E7%A5%A8%E5%8E%86%E5%8F%B2%E6%95%B0%E6%8D%AE%E4%B8%8B%E8%BD%BD This endpoint allows you to download historical market quotation data for a specified year. The data includes A-shares, STAR Market, ChiNext, stocks, and indices. ```APIDOC ## GET /query/history ### Description Downloads historical market quotation data for a specified year. This includes data for A-shares, STAR Market, ChiNext, stocks, and indices. ### Method GET ### Endpoint http://jvquant.com/query/history ### Parameters #### Query Parameters - **stamp** (string) - Required - Timestamp for the request. - **token** (string) - Required - Your account token for authentication. - **year** (string) - Required - The year for which to download data (e.g., "2020.zip"). ### Request Example ``` http://jvquant.com/query/history?stamp=1637374048&token=<账户Token>&year=2020.zip ``` ### Response #### Success Response (200) - **file** (zip) - The historical data for the specified year, packaged as a zip file. #### Response Example (A zip file containing historical market data for the year 2020) ```