Placing a TP profit and Stop loss order using CCXT and BINANCE

After trying many different ways of doing this with ByBit I gave Binance a shot. This seems to work fine and means that I dont have to worry about cancelling the tp/sl order if the other order is triggered!

def place_order(testmode, type, symbol, side, tp, sl, amount):
    try:
        # Get the market data
        market_data = get_market_bid_price(symbol)

        # Get the market price
        market_price = float(market_data)

        type = 'limit'  # or 'market'
        side = 'buy'
        price = market_price + 2  # your price
        exchange.load_markets()

        market = exchange.market(symbol)
        buyresponse = exchange.create_market_buy_order(
            market['id'],
            amount
        )
        print(buyresponse)
        response = exchange.private_post_order_oco({
            'symbol': market['id'],
            'side': 'SELL',  # SELL, BUY
            'quantity': exchange.amount_to_precision(symbol, amount),
            'price': exchange.price_to_precision(symbol, price),
            'stopPrice': exchange.price_to_precision(symbol, sl),
            'stopLimitPrice': exchange.price_to_precision(symbol, tp),  # If provided, stopLimitTimeInForce is required
            'stopLimitTimeInForce': 'GTC',  # GTC, FOK, IOC
        })
        logger(response)
    except Exception as e:
        logger(f"An error occurred while placing the order: {e}")


# Save the order details to a CSV file
    with open('orders.csv', mode='a') as file:
        writer = csv.writer(file)

        # Write the header row if the file is empty
        if file.tell() == 0:
            writer.writerow(ORDERCOLUMNS)

        # Write the order details
        writer.writerow([
            response['listClientOrderId'],
            datetime.datetime.now(),
            symbol,
            side,
            amount,
            market_price,
            tp,
            sl,
            response['orders'][0]['clientOrderId'],
            response['orders'][1]['clientOrderId'],
            ""
        ])
        return response

Posted

in

by

Comments

One response to “Placing a TP profit and Stop loss order using CCXT and BINANCE”

  1. […] UPDATE – I have since switched to Binance. Here is the post: Placing a TP profit and Stop loss order using CCXT and BINANCE […]

Leave a Reply

Your email address will not be published. Required fields are marked *