Introduction
Take profit (TP) and stop loss (SL) functions are critical for risk management in trading. This library simplifies TP/SL implementation across OKX, Binance, and Huobi exchanges by unifying their disparate APIs into a single Python function.
Key features:
- Supports isolated/cross margin modes
- Compatible with USDⓈ-M and COIN-M futures
- Avoids market-order fees via limit-order triggers
Core Function Implementation
Unified TP/SL Function
import json
def zhiyingzhisun(ex, amount, directionStr, zhiying, zhisun, cangType=0):
if ex.GetName().find('OK') >= 0:
return okexSwap(ex, amount, directionStr, zhiying, zhisun)
elif ex.GetName().find('Huobi') >= 0:
return huobiSwap(ex, amount, directionStr, zhiying, zhisun, cangType)
elif ex.GetName().find('Binance') >= 0:
return bianSwap(ex, amount, directionStr, zhiying, zhisun)
else:
return FalseExchange-Specific Handlers
1. Huobi Futures
def huobiSwap(ex, amount, directionStr, zhiying, zhisun, cangType):
instrument_id = ex.GetCurrency().replace('_',"-")
# URL selection based on margin type
if instrument_id.find('USDT') >= 0:
url = "/linear-swap-api/v1/swap_tpsl_order" if cangType == 0 else '/linear-swap-api/v1/swap_cross_tpsl_order'
elif instrument_id.find('USD') >= 0:
url = "/swap-api/v1/swap_tpsl_order"
else:
return False
data = AsynIo(ex, ['api', 'POST', url, '', json.dumps({
"contract_code": instrument_id,
"direction": directionStr,
"volume": amount,
"tp_trigger_price": zhiying,
"sl_trigger_price": zhisun,
})])
return data["status"] == 'ok'2. Binance Futures
def bianSwap(ex, amount, directionStr, zhiying, zhisun):
instrument_id = ex.GetCurrency().replace('_',"")
url = "/fapi/v1/order" if instrument_id.find('USDT') >= 0 else '/dapi/v1/order'
# SL order
zhisunData = AsynIo(ex, ['api', 'POST', url, '', json.dumps({
"symbol": instrument_id,
"type": "STOP",
"quantity": amount,
"stopPrice": zhisun,
})])
# TP order
zhiyingData = AsynIo(ex, ['api', 'POST', url, '', json.dumps({
"symbol": instrument_id,
"type": "TAKE_PROFIT",
"stopPrice": zhiying,
})])
return all((
int(zhisunData['stopPrice']) == int(zhisun),
int(zhiyingData['stopPrice']) == int(zhiying)
))3. OKX Futures
def okexSwap(ex, amount, directionStr, zhiying, zhisun):
instrument_id = ex.GetCurrency().replace('_',"-") + '-SWAP'
direction = '4' if directionStr == 'buy' else '3'
data = AsynIo(ex, ['api', 'POST', '/v1/order/orders/place', '', json.dumps({
"instrument_id": instrument_id,
"type": direction,
"order_type": '5',
"tp_trigger_price": zhiying,
"sl_trigger_price": zhisun,
})])
return data["error_code"] == "0"Integration Guide
Parameters
| Parameter | Description | Example |
|---|---|---|
ex | Exchange object | exchange |
amount | Position size | 10 |
directionStr | "buy" or "sell" | "sell" |
zhiying | Take profit price | 42000 |
zhisun | Stop loss price | 38000 |
cangType | 0=isolated, 1=cross margin | 1 |
FAQ
How do I add this to existing bots?
Simply import the script and call zhiyingzhisun() with your strategy's trade parameters.
Does this work with spot markets?
No, this library is designed exclusively for futures trading.
Why use limit orders instead of market orders?
Limit orders avoid taker fees and provide better price control during volatile markets.
Best Practices
- Test in sandbox environments before live deployment
- Monitor order status via exchange APIs
- Adjust TP/SL levels based on ATR or volatility metrics
👉 Optimize your trading strategy
Conclusion
This library eliminates exchange-specific complexities for TP/SL orders, offering a streamlined solution for multi-exchange trading systems. By handling margin types and contract specifications automatically, it reduces development overhead and minimizes implementation errors.