委托下單
該接口用於港美股,窩輪,期權的委托下單。
longbridge order buy TSLA.US 100 --price 250.00
longbridge order sell TSLA.US 100 --price 260.00
SDK Links
Python |
Rust |
Go |
Node.js |
Java |
C++ |
Request
| HTTP Method | POST |
| HTTP URL | /v1/trade/order |
Parameters
Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | YES | 股票代碼,使用 ticker.region 格式,例如:AAPL.US |
| order_type | string | YES | 訂單類型 |
| submitted_price | string | NO | 下單價格,例如:388.5LO / ELO / ALO / ODD / LIT 訂單必填 |
| submitted_quantity | string | YES | 下單數量,例如:100 |
| trigger_price | string | NO | 觸發價格,例如:388.5LIT / MIT 訂單必填 |
| limit_offset | string | NO | 指定價差TSLPAMT / TSLPPCT 訂單在 limit_depth_level 為 0 時必填 |
| trailing_amount | string | NO | 跟蹤金額TSLPAMT 訂單必填 |
| trailing_percent | string | NO | 跟蹤漲跌幅TSLPPCT 訂單必填 |
| expire_date | string | NO | 長期單過期時間,格式為 YYYY-MM-DD, 例如:2022-12-05time_in_force 為 GTD 時必填 |
| side | string | YES | 買賣方向 可選值: Buy - 買入Sell - 賣出 |
| outside_rth | string | NO | 是否允許盤前盤後,美股必填 可選值: RTH_ONLY - 不允許盤前盤後ANY_TIME - 允許盤前盤後OVERNIGHT - 夜盤OPTION_PRE_MARKET - 夜盤期權 |
| time_in_force | string | YES | 訂單有效期類型 可選值: Day - 當日有效GTC - 撤單前有效GTD - 到期前有效 |
| remark | string | NO | 備註 (最大 64 字符) |
| limit_depth_level | int32 | NO | 指定買賣檔位,取值範圍為 -5 ~ 0 ~ 5,負數代表買盤檔位(例如 -1 表示買一), 正數代表賣盤檔位(例如 1 表示賣一),當為 0 時 limit_offset 參數生效 TSLPAMT / TSLPPCT 訂單有效 |
| monitor_price | string | NO | 監控價格,需要達到該價格才會開始監控,更新參考價TSLPAMT / TSLPPCT 訂單有效 |
| trigger_count | int32 | NO | 觸發次數,取值範圍 0 ~ 3,表示在 1 分鐘內觸發多次才會觸發訂單,LIT / MIT / TSLPAMT / TSLPPCT 訂單有效 |
| client_request_id | string | NO | 冪等性請求 ID,用於防止重複下單。服務器會快取該請求 ID 10 分鐘。在此期間內如果收到相同 ID 的請求,將返回原始響應而不建立重複訂單。必須是唯一標識符(如 UUID)。 |
| attached_params | object | NO | 附加單參數(止盈止損) |
| attached_params.attached_order_type | string | NO | 附加單訂單類型 可選值: PROFIT_TAKER - 止盈STOP_LOSS - 止損BRACKET - 括號單 |
| attached_params.profit_taker_price | string | NO | 止盈觸發價格 |
| attached_params.stop_loss_price | string | NO | 止損觸發價格 |
| attached_params.time_in_force | string | NO | 附加單有效期類型 可選值: Day - 當日有效GTC - 撤單前有效GTD - 到期前有效(此時繼承主單 expire_date) |
| attached_params.expire_time | int64 | NO | 到期時間(Unix 時間戳,單位秒) |
| attached_params.activate_order_type | string | NO | 觸發後提交的訂單類型,例如 LIT(限價單)或 MIT(市價單) |
| attached_params.profit_taker_submit_price | string | NO | 止盈限價委託價格,activate_order_type 為 LIT 時必填 |
| attached_params.stop_loss_submit_price | string | NO | 止損限價委託價格,activate_order_type 為 LIT 時必填 |
| attached_params.activate_rth | string | NO | 觸發後提交的訂單是否允許盤前盤後 可選值: RTH_ONLY - 不允許盤前盤後ANY_TIME - 允許盤前盤後 |
冪等性
為了防止由於網路重試或客戶端故障而導致訂單重複,您可以使用 client_request_id 參數:
- 用途:防止相同請求重試時建立重複訂單
- 快取時長:10 分鐘(服務器端)
- 格式:每個請求需要一個唯一字符串(如 UUID 或自定義標識符)
- 行為:如果在 10 分鐘內收到相同的
client_request_id,服務器將返回原始請求的快取響應,而不建立新訂單
冪等性示例
首次請求:client_request_id="abc123-uuid-request" → 建立訂單,ID 為 12345
重試請求(10 分鐘內,相同 ID):client_request_id="abc123-uuid-request" → 返回現有訂單 ID 12345(無重複)
新請求:client_request_id="xyz789-uuid-request" → 建立新訂單
不傳 client_request_id 的情況
如果不提供 client_request_id(或傳空值),請求仍會正常成功並建立訂單。但是冪等攔截將被跳過,這意味著:
- 每個請求(即使內容完全相同)都會建立單獨的訂單
- 網路重試或意外重複請求可能導致訂單重複
- 服務器不會對該請求進行快取
強烈建議在關鍵下單操作中始終提供唯一的 client_request_id,以防止意外的重複訂單。
Request Example
from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Create a context for trade APIs
ctx = TradeContext(config)
# Submit order
resp = ctx.submit_order("700.HK", OrderType.LO, OrderSide.Buy, Decimal(500), TimeInForceType.Day, submitted_price=Decimal(50), remark="Hello from Python SDK")
print(resp)import asyncio
from decimal import Decimal
from longbridge.openapi import AsyncTradeContext, Config, OrderType, OrderSide, TimeInForceType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Create a context for trade APIs
ctx = AsyncTradeContext.create(config)
# Submit order
resp = await ctx.submit_order("700.HK", OrderType.LO, OrderSide.Buy, Decimal(500), TimeInForceType.Day, submitted_price=Decimal(50), remark="Hello from Python SDK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())const { Config, TradeContext, OAuth, OrderType, OrderSide, TimeInForceType, Decimal } = require('longbridge')
async function main() {
const oauth = await OAuth.build("your-client-id", (_, url) => { console.log("Open this URL to authorize: " + url) })
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.submitOrder({ symbol: "700.HK", orderType: OrderType.LO, side: OrderSide.Buy, submittedQuantity: new Decimal(500), timeInForce: TimeInForceType.Day, submittedPrice: new Decimal(50), remark: "Hello" })
console.log(resp)
}
main().catch(console.error)import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
SubmitOrderResponse resp = ctx.submitOrder(new SubmitOrderOptions("700.HK", OrderType.LO, OrderSide.Buy, new BigDecimal("500"), TimeInForceType.Day).setSubmittedPrice(new BigDecimal("50")).setRemark("Hello")).get();
System.out.println(resp.orderId);
}
}
}use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, SubmitOrderOptions, OrderType, OrderSide, TimeInForceType}, Config};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.submit_order(
SubmitOrderOptions::new("700.HK", OrderType::LO, OrderSide::Buy, Decimal::from(500), TimeInForceType::Day)
.submitted_price(Decimal::from(50))
.remark("Hello")
).await?;
println!("{:?}", resp);
Ok(())
}#include <iostream>
#include <longbridge.hpp>
#ifdef WIN32
#include <windows.h>
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
SubmitOrderOptions opts{"700.HK", OrderType::LO, OrderSide::Buy, 200, TimeInForceType::Day, Decimal(50.0), std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt};
ctx.submit_order(opts, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "order_id: " << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
"github.com/shopspring/decimal"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
orderID, err := tctx.SubmitOrder(context.Background(), &trade.SubmitOrder{
Symbol: "700.HK",
OrderType: trade.OrderTypeLO,
Side: trade.OrderSideBuy,
SubmittedQuantity: 500,
SubmittedPrice: decimal.NewFromFloat(50),
TimeInForce: trade.TimeTypeDay,
Remark: "Hello from Go SDK",
})
if err != nil {
log.Fatal(err)
}
fmt.Println("order_id:", orderID)
}Response
Response Headers
- Content-Type: application/json
Response Example
{
"code": 0,
"message": "success",
"data": {
"order_id": 683615454870679600
}
}
Response Status
| Status | Description | Schema |
|---|---|---|
| 200 | 提交成功,訂單已委托。 | None |
| 400 | 下單被拒絕,請求參數錯誤。 | None |