Skip to content

Commit 416811f

Browse files
paul-lestyocarlosmiei
authored andcommitted
feat: Update futures algo order API with new TP/SL parameters (sammchardy#1672)
* feat: Update futures algo order API with new TP/SL parameters - Enhanced futures_create_algo_order() to support new API parameters: * priceMatch: for LIMIT/STOP/TAKE_PROFIT orders (OPPONENT/QUEUE options) * priceProtect: price protection for STOP_MARKET/TAKE_PROFIT_MARKET * activatePrice & callbackRate: for TRAILING_STOP_MARKET orders * selfTradePreventionMode: STP modes (EXPIRE_TAKER/MAKER/BOTH) * goodTillDate: for GTD time in force * newOrderRespType: ACK or RESULT response type * workingType: trigger based on MARK_PRICE or CONTRACT_PRICE * closePosition: close all positions * reduceOnly: reduce only mode * timeInForce: IOC/GTC/FOK/GTX support * positionSide: LONG/SHORT for hedge mode - Updated comprehensive documentation with all parameter descriptions - Added practical code example in docstring - Created 12 new test cases for both sync and async clients: * Test priceProtect parameter * Test trailing stop with activatePrice/callbackRate (skipped for testnet) * Test selfTradePreventionMode * Test priceMatch parameter * Test newOrderRespType parameter * Test workingType parameter - Added examples/futures_algo_order_examples.py with practical usage examples This update aligns with the latest Binance Futures API documentation for New Algo Order endpoint supporting advanced TP/SL functionality. Note: Some tests may fail in testnet due to timestamp sync issues, which is a known testnet limitation, not a code issue. * fix linting --------- Co-authored-by: carlosmiei <43336371+carlosmiei@users.noreply.github.com>
1 parent 2b048bf commit 416811f

File tree

4 files changed

+553
-4
lines changed

4 files changed

+553
-4
lines changed

binance/client.py

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8204,25 +8204,64 @@ def futures_create_algo_order(self, **params):
82048204

82058205
https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order
82068206

8207+
:param algoType: required - Only support CONDITIONAL
8208+
:type algoType: str
82078209
:param symbol: required
82088210
:type symbol: str
82098211
:param side: required - BUY or SELL
82108212
:type side: str
8211-
:param type: required - STOP, TAKE_PROFIT, STOP_MARKET, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET
8213+
:param positionSide: optional - Default BOTH for One-way Mode; LONG or SHORT for Hedge Mode
8214+
:type positionSide: str
8215+
:param type: required - STOP_MARKET/TAKE_PROFIT_MARKET/STOP/TAKE_PROFIT/TRAILING_STOP_MARKET
82128216
:type type: str
8213-
:param quantity: optional
8217+
:param timeInForce: optional - IOC or GTC or FOK or GTX, default GTC
8218+
:type timeInForce: str
8219+
:param quantity: optional - Cannot be sent with closePosition=true
82148220
:type quantity: decimal
82158221
:param price: optional
82168222
:type price: decimal
82178223
:param triggerPrice: optional - Used with STOP, STOP_MARKET, TAKE_PROFIT, TAKE_PROFIT_MARKET
82188224
:type triggerPrice: decimal
8219-
:param algoType: required - CONDITIONAL
8220-
:type algoType: str
8225+
:param workingType: optional - triggerPrice triggered by: MARK_PRICE, CONTRACT_PRICE. Default CONTRACT_PRICE
8226+
:type workingType: str
8227+
:param priceMatch: optional - only available for LIMIT/STOP/TAKE_PROFIT order
8228+
:type priceMatch: str
8229+
:param closePosition: optional - true, false; Close-All, used with STOP_MARKET or TAKE_PROFIT_MARKET
8230+
:type closePosition: str
8231+
:param priceProtect: optional - "TRUE" or "FALSE", default "FALSE"
8232+
:type priceProtect: str
8233+
:param reduceOnly: optional - "true" or "false", default "false"
8234+
:type reduceOnly: str
8235+
:param activatePrice: optional - Used with TRAILING_STOP_MARKET orders
8236+
:type activatePrice: decimal
8237+
:param callbackRate: optional - Used with TRAILING_STOP_MARKET orders, min 0.1, max 10
8238+
:type callbackRate: decimal
8239+
:param clientAlgoId: optional - A unique id among open orders
8240+
:type clientAlgoId: str
8241+
:param newOrderRespType: optional - "ACK", "RESULT", default "ACK"
8242+
:type newOrderRespType: str
8243+
:param selfTradePreventionMode: optional - EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, default NONE
8244+
:type selfTradePreventionMode: str
8245+
:param goodTillDate: optional - order cancel time for timeInForce GTD
8246+
:type goodTillDate: long
82218247
:param recvWindow: optional - the number of milliseconds the request is valid for
82228248
:type recvWindow: int
82238249

82248250
:returns: API response
82258251

8252+
.. code-block:: python
8253+
8254+
result = client.futures_create_algo_order(
8255+
algoType='CONDITIONAL',
8256+
symbol='BNBUSDT',
8257+
side='SELL',
8258+
type='TAKE_PROFIT',
8259+
quantity='0.01',
8260+
price='750.000',
8261+
triggerPrice='750.000',
8262+
timeInForce='GTC'
8263+
)
8264+
82268265
"""
82278266
if "clientAlgoId" not in params:
82288267
params["clientAlgoId"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
#!/usr/bin/env python
2+
"""
3+
Examples of how to use the Futures Algo Order API.
4+
5+
New Algo Order supports various conditional order types including:
6+
- STOP / STOP_MARKET
7+
- TAKE_PROFIT / TAKE_PROFIT_MARKET
8+
- TRAILING_STOP_MARKET
9+
10+
This example demonstrates the new parameters and features available
11+
for creating advanced algo orders with TP/SL functionality.
12+
"""
13+
14+
from binance.client import Client
15+
16+
# Initialize the client
17+
api_key = '<api_key>'
18+
api_secret = '<api_secret>'
19+
client = Client(api_key, api_secret)
20+
21+
22+
def create_basic_stop_market_order():
23+
"""Create a basic STOP_MARKET algo order"""
24+
order = client.futures_create_algo_order(
25+
symbol='BTCUSDT',
26+
side='SELL',
27+
type='STOP_MARKET',
28+
quantity=0.001,
29+
triggerPrice=40000,
30+
workingType='CONTRACT_PRICE'
31+
)
32+
print("Basic Stop Market Order:", order)
33+
return order
34+
35+
36+
def create_take_profit_with_price_protect():
37+
"""Create a TAKE_PROFIT order with price protection enabled"""
38+
order = client.futures_create_algo_order(
39+
symbol='BTCUSDT',
40+
side='SELL',
41+
type='TAKE_PROFIT',
42+
quantity=0.001,
43+
price=50000,
44+
triggerPrice=50000,
45+
timeInForce='GTC',
46+
priceProtect='TRUE',
47+
workingType='MARK_PRICE'
48+
)
49+
print("Take Profit with Price Protection:", order)
50+
return order
51+
52+
53+
def create_trailing_stop_market():
54+
"""Create a TRAILING_STOP_MARKET order with activate price and callback rate"""
55+
order = client.futures_create_algo_order(
56+
symbol='BTCUSDT',
57+
side='SELL',
58+
type='TRAILING_STOP_MARKET',
59+
quantity=0.001,
60+
activatePrice=48000, # Activate when price reaches this level
61+
callbackRate=1.0, # 1% callback rate
62+
)
63+
print("Trailing Stop Market:", order)
64+
return order
65+
66+
67+
def create_stop_with_stp_mode():
68+
"""Create a STOP order with Self-Trade Prevention mode"""
69+
order = client.futures_create_algo_order(
70+
symbol='BTCUSDT',
71+
side='BUY',
72+
positionSide='LONG', # For hedge mode
73+
type='STOP',
74+
quantity=0.001,
75+
price=42000,
76+
triggerPrice=42000,
77+
timeInForce='GTC',
78+
selfTradePreventionMode='EXPIRE_MAKER'
79+
)
80+
print("Stop Order with STP Mode:", order)
81+
return order
82+
83+
84+
def create_take_profit_with_price_match():
85+
"""Create a TAKE_PROFIT order with price match parameter"""
86+
order = client.futures_create_algo_order(
87+
symbol='BTCUSDT',
88+
side='SELL',
89+
type='TAKE_PROFIT',
90+
quantity=0.001,
91+
triggerPrice=50000,
92+
timeInForce='GTC',
93+
priceMatch='OPPONENT', # Match opponent's price
94+
)
95+
print("Take Profit with Price Match:", order)
96+
return order
97+
98+
99+
def create_stop_market_close_position():
100+
"""Create a STOP_MARKET order to close all positions"""
101+
order = client.futures_create_algo_order(
102+
symbol='BTCUSDT',
103+
side='SELL',
104+
type='STOP_MARKET',
105+
closePosition='true', # Close all current long positions
106+
triggerPrice=39000,
107+
priceProtect='TRUE'
108+
)
109+
print("Stop Market Close Position:", order)
110+
return order
111+
112+
113+
def create_stop_with_reduce_only():
114+
"""Create a STOP order with reduce only mode"""
115+
order = client.futures_create_algo_order(
116+
symbol='BTCUSDT',
117+
side='SELL',
118+
type='STOP',
119+
quantity=0.001,
120+
price=41000,
121+
triggerPrice=41000,
122+
timeInForce='GTC',
123+
reduceOnly='true' # Only reduce position, not increase
124+
)
125+
print("Stop with Reduce Only:", order)
126+
return order
127+
128+
129+
def create_with_good_till_date():
130+
"""Create an algo order with GTD (Good Till Date) time in force"""
131+
import time
132+
# Set expiry to 1 hour from now (timestamp in milliseconds)
133+
expiry_time = int((time.time() + 3600) * 1000)
134+
135+
order = client.futures_create_algo_order(
136+
symbol='BTCUSDT',
137+
side='SELL',
138+
type='TAKE_PROFIT',
139+
quantity=0.001,
140+
price=50000,
141+
triggerPrice=50000,
142+
timeInForce='GTD',
143+
goodTillDate=expiry_time
144+
)
145+
print("Order with Good Till Date:", order)
146+
return order
147+
148+
149+
def create_with_result_response():
150+
"""Create an algo order with RESULT response type for detailed information"""
151+
order = client.futures_create_algo_order(
152+
symbol='BTCUSDT',
153+
side='BUY',
154+
type='STOP_MARKET',
155+
quantity=0.001,
156+
triggerPrice=42000,
157+
newOrderRespType='RESULT' # Get detailed response
158+
)
159+
print("Order with RESULT response:", order)
160+
return order
161+
162+
163+
def query_algo_order(symbol, algo_id):
164+
"""Query a specific algo order status"""
165+
order = client.futures_get_algo_order(
166+
symbol=symbol,
167+
algoId=algo_id
168+
)
169+
print("Algo Order Status:", order)
170+
return order
171+
172+
173+
def query_open_algo_orders(symbol=None):
174+
"""Query all open algo orders"""
175+
if symbol:
176+
orders = client.futures_get_open_algo_orders(symbol=symbol)
177+
else:
178+
orders = client.futures_get_open_algo_orders()
179+
print("Open Algo Orders:", orders)
180+
return orders
181+
182+
183+
def cancel_algo_order(symbol, algo_id):
184+
"""Cancel a specific algo order"""
185+
result = client.futures_cancel_algo_order(
186+
symbol=symbol,
187+
algoId=algo_id
188+
)
189+
print("Cancel Result:", result)
190+
return result
191+
192+
193+
def cancel_all_algo_orders(symbol):
194+
"""Cancel all open algo orders for a symbol"""
195+
result = client.futures_cancel_all_algo_open_orders(symbol=symbol)
196+
print("Cancel All Result:", result)
197+
return result
198+
199+
200+
if __name__ == '__main__':
201+
# Example usage
202+
print("=" * 50)
203+
print("Futures Algo Order Examples")
204+
print("=" * 50)
205+
206+
# Create different types of algo orders
207+
# Uncomment the examples you want to try
208+
209+
# order = create_basic_stop_market_order()
210+
# order = create_take_profit_with_price_protect()
211+
# order = create_trailing_stop_market()
212+
# order = create_stop_with_stp_mode()
213+
# order = create_take_profit_with_price_match()
214+
# order = create_with_result_response()
215+
216+
# Query orders
217+
# orders = query_open_algo_orders('BTCUSDT')
218+
219+
# Cancel orders
220+
# cancel_algo_order('BTCUSDT', algo_id=12345)
221+
# cancel_all_algo_orders('BTCUSDT')

0 commit comments

Comments
 (0)