sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
5.96k stars 2.19k forks source link

How to create TP/SL orders after creating limit order #1229

Open buckydroid opened 2 years ago

buckydroid commented 2 years ago

For example let's say the current price is 80 and I want to create a new limit order at 100. But after creating limit order I want to set a stop loss at 95 and take profit at 105.

So I tried doing something like the following,

order = client.futures_create_order(symbol=symbol, side=client.SIDE_BUY, newClientOrderId = crypto, type='LIMIT', quantity=qty, price=price, timeInForce="GTC")   
print(order)

open_order_id = order['orderId']    

print("TP Order")
order = client.futures_create_order(symbol=symbol, side=client.SIDE_SELL,  newClientOrderId= crypto+"_TP",quantity=qty, type=client.FUTURE_ORDER_TYPE_TAKE_PROFIT, stopPrice=tp, price=tp,  timeInForce="GTC", reduceOnly = True)     
print(order)

print("SL Order")
order = client.futures_create_order(symbol=symbol, side=client.SIDE_SELL,  newClientOrderId= crypto+"_SL",quantity=qty, type=client.FUTURE_ORDER_TYPE_STOP, stopPrice=sl, price=sl,  timeInForce="GTC", reduceOnly = True)     
print(order)

This works fine when the price is at 99 and I want to create a limit order at 100 with 95 SL or 105 TP. But in the first case, it gives me an error that this order would trigger immediately. Which kinda makes sense...

But is there any other methods or api I can use to create tp sl order for a limit order independent of the current price?

KazutoMartin commented 1 year ago

Hi

This is what I personally did and it worked for me

You need to first create your limit order, and wait for it to open a position When the position is opened and active, then you can set your TP/SL

You can connect to user socket stream (How to connect to user data stream) to get updates for your orders wait for it to give you the FILLED status of your sent order When you get the FILLED update of your order, set your TP/SL

Trading-Mark commented 1 year ago

Having the problem here. Man would think that arg closePosition=True or reduceOnly=True would get rid of "immediately" error. That is not the case. Do not know what is the reason for those 2 arguments to exist if adding BUY and SELL order closes eachother anyways...