Skip to main content

Command Palette

Search for a command to run...

Buy an Asset and instantly create a Take Profit and Stop Loss OCO Sell Order using Python in Binance Isolated Margin

Buy an Asset and instantly create a Take Profit and Stop Loss OCO Sell Order using Python in Binance Isolated Margin

Published
2 min read
Buy an Asset and instantly create a Take Profit and Stop Loss OCO Sell Order using Python in Binance Isolated Margin
O
I build systems that work — technically sound, security-first, and actually useful to the people who depend on them. Creator of the UNICORN Binance Suite — 6 open source Python libraries with 2.8M+ PyPI downloads and 388+ dependent public projects. Currently pioneering AI-driven open source maintenance: running a controlled AI agent that maintains production code and documenting what it means for engineering teams. Vienna, Austria 🇦🇹

Automate your Binance trading strategy by creating OCO sell orders with Python in isolated margin accounts.

There is always the justified desire to buy an asset and at the same time to create a take profit and a stop loss order. In this way, if a profit is made, the asset is sold and any risks are minimized.

This strategy consists of two orders: a BUY and an OCO SELL order.

OCO stands for "One Cancells the Other" and creates both a sell order for Take Profit and one for Stop Loss:

In this tutorial we will create a Market Buy Order for Binance Isolated Margin in a Python Script and buy some BTC with 15 USDT. We will take the purchased amount of BTC and use it to create an OCO Sell Order that includes both Take Profit and Stop Loss (LIMIT).

In order for the code from this example to work for you, you need to transfer at least 15 USDT to your Isolated Margin account on Binance and you need an API key/secret pair from Binance.com.

Ok, here we go :)

First, make sure that the latest UNICORN Binance REST API version is installed:

$ python3 -m pip install unicorn-binance-rest-api --upgrade

Download this script and enter your API key/secret pair:

https://gist.github.com/oliver-zehentleitner/be1c4880b79db7596cf40b7d169b72f6

The comments in the script should help you understand the code.

Watch this video to see how I start the script and what happens on Binance:

https://youtu.be/iuwoweIFJL4


I hope you found this tutorial informative and enjoyable!

Follow me on Binance Square, GitHub, X and LinkedIn to stay updated on my latest releases. Your constructive feedback is always appreciated!

Thank you for reading, and happy coding!

UNICORN Binance Suite

Part 1 of 11

Open source Python libraries for automated trading on Binance — WebSocket streams, REST API, local order books, trailing stop loss, and Kubernetes-scale depth caching. Engineering decisions, real-world findings, and lessons from production.

Up next

Passing Binance Market Data to Apache Kafka in Python with aiokafka

Learn how to create an Apache Kafka cluster and store Binance data in it in real time.