2 min read

How to Cancel an Order on Binance with Python

Learn how to cancel an order programmatically on Binance using Python.
Cute little clockwork robot holding a red arrow with steps point up
Python Trading Bot

Python Trading Bot

There are times in your automated trading where you need to cancel an order. Doing this programmatically can save you time and ensure you cancel exactly what you need.

If you’re building a crypto trading bot using Binance, then this function will help you cancel your order.


Assumptions

To use this function, I’ll be assuming that you:

  1. Have connected to Binance using your api_key and secret_key
  2. Are cancelling the order using the symbol as the filter (with a little modification you could also use other filters)
  3. May at times want to use the Binance Testnet
  4. Understand that all trading is at your own risk

P.S. If you’d like to see a tutorial on how to build a fully featured Binance Crypto Bot using Python, check out my series.

Code

What you need

  1. symbol to cancel the orders on
  2. project_settings is a JSON dictionary which holds your api_key and secret_key OR for the testnet your test_api_key and test_secret_key
  3. The Official Binance Python Wrapper from binance.spot import Spot

Function

# Function to cancel a trade
def cancel_order_by_symbol(symbol, project_settings):
    # See if we're testing. Default to yes.
    if project_settings['Testing'] == "False":
        # Set the API Key
        api_key = project_settings['BinanceKeys']['API_Key']
        # Set the secret key
        secret_key = project_settings['BinanceKeys']['Secret_Key']
        # Setup the client
        client = Spot(key=api_key, secret=secret_key)
    else:
        print("Testing Trading")
        # Set the Test API Key
        api_key = project_settings['TestKeys']['Test_API_Key']
        # Set the Test Secret Key
        secret_key = project_settings['TestKeys']['Test_Secret_Key']
        client = Spot(key=api_key, secret=secret_key, base_url="https://testnet.binance.vision")

    # Cancel the trade
    try:
        response = client.cancel_open_orders(symbol=symbol)
        return response
    except ConnectionRefusedError as error:
        print(f"Found error {error}")

Say Hi!

I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.