Automated trading has transformed how investors manage risk and capture profits in fast-moving cryptocurrency markets. The OKX V5 API offers powerful tools for executing conditional orders—specifically stop-loss and take-profit strategies—that help traders protect capital and lock in gains without constant monitoring. This guide dives into the practical implementation of these functions using code-ready examples, ensuring you can integrate robust risk management directly into your algorithmic trading systems.
Whether you're building a high-frequency bot or a long-term position manager, understanding how to use the /api/v5/trade/order-algo endpoint effectively is essential. We'll walk through each function step by step, explain key parameters, and show how to deploy them in real-world scenarios.
Understanding Conditional Orders on OKX
Conditional (or algo) orders allow traders to set rules that trigger trades when specific market conditions are met. On the OKX V5 API, two primary types support risk control:
- Stop-Loss (SL): Minimizes losses if the price moves against your position.
- Take-Profit (TP): Automatically closes a position when a desired profit level is reached.
These can be submitted individually or combined using an OCO (One-Cancels-the-Other) order, where placing both TP and SL ensures only one executes—once either triggers, the other is canceled automatically.
👉 Discover how automated trading tools can enhance your strategy execution
Core Functions for Long Positions
When holding a long position, you profit as the price rises. To manage risk, you need mechanisms to exit if the market reverses or reaches a target gain.
1. Setting a Stop-Loss for Long Positions
The longStopLossInOkex() function places a conditional sell order that activates if the price drops to a specified level.
function longStopLossInOkex(num, symbol, price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=sell" + "&posSide=long" + "&ordType=conditional" + "&sz=" + size.toString() + "&slTriggerPx=" + price.toString() + "&slOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂多单止损:", ret);
return true;
}instId: Converts input symbol (e.g., ETH_USDT) to OKX’s swap format.slTriggerPx: The price that triggers the stop-loss.slOrdPx=-1: Sets market execution upon trigger.
2. Setting a Take-Profit for Long Positions
Use longTakeProfitInOkex() to lock in profits when prices rise.
function longTakeProfitInOkex(num, symbol, price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=sell" + "&posSide=long" + "&ordType=conditional" + "&sz=" + size.toString() + "&tpTriggerPx=" + price.toString() + "&tpOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂多单止盈:", ret);
return true;
}This works similarly but uses tpTriggerPx to define the take-profit threshold.
3. Combining Both with OCO Orders
For comprehensive protection, use longTpAndSlInOkex() to place both orders simultaneously:
function longTpAndSlInOkex(num, symbol, tp_price, sl_price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=sell" + "&posSide=long" + "&ordType=oco" + "&sz=" + size.toString() +
"&tpTriggerPx=" + tp_price.toString() + "&tpOrdPx=-1" +
"&slTriggerPx=" + sl_price.toString() + "&slOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂多单止盈止损:", ret);
return true;
}Using "ordType=oco" ensures that if the take-profit executes, the stop-loss is canceled—and vice versa.
Managing Short Positions
Short sellers profit from falling prices and must protect themselves from upward price surges.
1. Stop-Loss for Short Positions
The shortStopLossInOkex() function sells higher than entry to limit losses:
function shortStopLossInOkex(num, symbol, price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=buy" + "&posSide=short" + "&ordType=conditional" + "&sz=" + size.toString() + "&slTriggerPx=" + price.toString() + "&slOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂空单止损:", ret);
return true;
}Note: For shorts, a stop-loss means buying back at a higher price (side=buy).
2. Take-Profit for Short Positions
To secure gains when price declines, use shortTakeProfitInOkex():
function shortTakeProfitInOkex(num, symbol, price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=buy" + "&posSide=short" + "&ordType=conditional" + "&sz=" + size.toString() + "&tpTriggerPx=" + price.toString() + "&tpOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂空单止盈:", ret);
return true;
}Again, this triggers a buy-to-close action when the price hits the target.
3. OCO Order for Shorts
Combine both with shortTpAndSlInOkex():
function shortTpAndSlInOkex(num, symbol, tp_price, sl_price, size) {
let real_symbol = symbol.replace("_USDT", "") + "-USDT-SWAP";
var param = "instId=" + real_symbol + "&tdMode=cross" + "&side=buy" + "&posSide=short" + "&ordType=oco" + "&sz=" + size.toString() +
"&tpTriggerPx=" + tp_price.toString() + "&tpOrdPx=-1" +
"&slTriggerPx=" + sl_price.toString() + "&slOrdPx=-1";
var ret = exchanges[num].IO("api", "POST", "/api/v5/trade/order-algo", param);
Log(exchanges[num].GetLabel(), ": 挂空单止盈止损:", ret);
return true;
}This ensures disciplined exits regardless of market direction.
Practical Example: Deploying Strategies
Here’s how to call these functions in practice:
function main() {
shortTakeProfitInOkex(0, "ETH_USDT", 2800, 1);
shortTpAndSlInOkex(0, "ETH_USDT", 2800, 3000, 1);
}This script:
- Sets a take-profit at $2800 for a short ETH position.
- Adds a stop-loss at $3000 to limit downside risk.
- Uses OCO logic so only one order executes.
👉 See how professional traders automate their risk controls with advanced APIs
Frequently Asked Questions (FAQ)
Q: What does tdMode=cross mean?
A: It specifies cross-margin mode, where your entire account balance supports the position. Alternatively, use isolated for position-specific margin isolation.
Q: Why use -1 for slOrdPx or tpOrdPx?
A: A value of -1 tells the system to execute at market price when triggered. You can set a limit price instead for more control.
Q: Can I modify or cancel an active conditional order?
A: Yes. Use the /api/v5/trade/cancel-algos endpoint with the algo ID returned during creation.
Q: Are these functions compatible with spot trading?
A: No. These are designed for perpetual swap contracts (-USDT-SWAP). Spot markets require different endpoints and parameters.
Q: How do I handle errors from the API response?
A: Always check the ret object for code and msg. Common issues include insufficient margin, invalid prices, or rate limits.
Q: Is there a rate limit on algo orders?
A: Yes. OKX enforces rate limits based on account tier. Exceeding them may result in temporary bans. Implement delays or batching in high-frequency setups.
Key Keywords
- OKX V5 API
- Stop-loss automation
- Take-profit strategy
- Conditional order trading
- Algo order integration
- Cryptocurrency risk management
- Perpetual swap API
- Automated trading scripts
These terms reflect core search intents related to algorithmic trading on OKX and are naturally integrated throughout this guide to boost SEO visibility while maintaining clarity and usefulness.
👉 Start building smarter trading strategies with powerful API tools today