How to place a bracket order on Binance through API?

172 Views Asked by At

Let's assume that I have buy_price, given I want to buy x quantity of that coin.

If the buy order is executed I want to execute a OCO order which would ensure to take profit on a certain price that would be greater than buy_price lets assume that as take_profit_price and sell if price drops below a stop loss price let's say that is stop_loss_price.

I am able to find OCO order that solve a part of the problem but I can't find any other order type that fits this scenario?

How can I accomplish this order in an automated way?

2

There are 2 best solutions below

4
simbullar On

Assuming you use binance api and have your api key and client secret...

from binance.client import Client

# Replace 'YOUR_API_KEY' and 'YOUR_API_SECRET' with your Binance API key and secret

client = Client(api_key='YOUR_API_KEY', api_secret='YOUR_API_SECRET')

def place_buy_order(symbol, quantity, buy_price, take_profit_price, stop_loss_price):
    # Place a limit buy order
    buy_order = client.create_order(
        symbol=symbol,
        side='BUY',
        type='LIMIT',
        timeInForce='GTC',  # Good 'til cancelled
        quantity=quantity,
        price=buy_price
    )

    # Calculate target prices for take profit and stop loss
    take_profit_price = buy_price * (1 + take_profit_price)
    stop_loss_price = buy_price * (1 - stop_loss_price)

    # Place an OCO order for take profit and stop loss
    oco_order = client.create_oco_order(
        symbol=symbol,
        quantity=quantity,
        price=take_profit_price,
        stopPrice=stop_loss_price,
        stopLimitPrice=stop_loss_price,  # Stop limit price for the stop loss order
        stopLimitTimeInForce='GTC'  # Good 'til cancelled
    )

    return buy_order, oco_order

# Example usage
symbol = 'BTCUSDT'
quantity = 1.0
buy_price = 40000.0
take_profit_percent = 0.05  # 5% take profit
stop_loss_percent = 0.03  # 3% stop loss

buy_order, oco_order = place_buy_order(symbol, quantity, buy_price, take_profit_percent, stop_loss_percent)

print("Buy Order:", buy_order)
print("OCO Order:", oco_order)

Basically, place_buy_order is creating the order for some cryptocurency which symbol is in symbol variable, quantity is in quantity and price is in buy_price. Then we calculate target price ad stop loss price. Then we also do an oco order and returing values buy_order and oco_order.

And then comes the example with BTCUSDT for 40000 with 5% take profit and 3% loss price. After buying we print out orders and we are done.

0
stahh On

An addition to the example below. You can add more exception or different verification

buy_order = client.create_order(
        ...
    )
# Response: {'symbol': 'LTCUSDT', 'orderId': 39144120110, **** 'status': 'NEW', ****}
order_id = buy_order.get('orderId')
status = buy_order.get('status')
start = time.time()
ttl = 180
while time.time() - start < ttl:
    try:
        status = client.get_order(symbol, orderId=order_id).get('status')
    except Exception as e:
        print(f'Something wrong: {e}')
        break
    if  status = 'FILLED':
        # Calculate target prices for take profit and stop loss
        take_profit_price = buy_price * (1 + take_profit_price)
        stop_loss_price = buy_price * (1 - stop_loss_price)

        # Place an OCO order for take profit and stop loss
        oco_order = client.create_oco_order(
            ...
        )
        break
    time.sleep(1)