How to Cancel an Order on Binance with Python
Learn how to cancel an order programmatically on Binance using Python.
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:
- Have connected to Binance using your
api_key
andsecret_key
- Are cancelling the order using the
symbol
as the filter (with a little modification you could also use other filters) - May at times want to use the Binance Testnet
- 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
symbol
to cancel the orders onproject_settings
is a JSON dictionary which holds yourapi_key
andsecret_key
OR for the testnet yourtest_api_key
andtest_secret_key
- 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.
❤