Today we're going to learn how to write a simple trading system that places trades on the Binance crypto exchange. At the end of this article, you'd be able to:

  • Retrieve your balance using your API keys.
  • Open and Close trades on your Binance Account.

This article will be written in Python, you can download the latest version of python here. This same article will be written in TypeScript for our lovely node.js devs out there and here's the link to it.

Disclaimer: The trading system provided in this article is for educational purposes alone. Do not use it for live trading until you have designed and backtested a robust trading system. Let's get started.

Setting up the Environment and Installing Dependencies

Create the project folder, we'll call it Binance_Bot. Inside the project folder, we'll create 3 files:

  1. app.py (This file is where we write the bot logic)
  2. requirements.txt (This file is where we store our dependencies)
  3. .env (This file is an environment variable file, we can store our API keys in it)
  4. .gitignore (This file is to prevent us from accidentally pushing our keys to Github)

Now we'll need to get our dependencies; open up requirements.txt and include these packages:

python-dotenv
ccxt

After adding those to the requirements.txt file, on your terminal, navigate into the project directory and run this command.

$ pip3 install -r requirements.txt

It installs all the dependencies required for this simple bot.

Generating API keys and Storing them Securely

We'll be using the Binance crypto exchange for this article, if you don't have an account with them you can register by clicking this link

After creating an account, you'll have to generate API keys, you can read this article to easily do that, be sure to copy your API key and secret as we'll use them in a moment.

Now that you have your API keys, it's time to store them as environment variables, that way we don't write them in our script that we'll likely push to Github. So open up your .env file with your IDE and include this:

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

Some crypto exchanges require a password but Binance only needs your API key and secret. Now open up the .gitignore file and write

.env

And that way, our API keys remain saved on our PC alone and do not get pushed to a server or uploaded to the internet.

Now that our keys have been securely saved, it's time to import them to our app.py script.

from dotenv import load_dotenv
import os, json 

load_dotenv()  # Take environment variables from .env

The CCXT Library

The CCXT library is an amazing library used to connect and trade with cryptocurrency exchanges. It provides quick access to market data for storage, analysis, visualization, indicator development, algorithmic trading, strategy backtesting, bot programming, and related software engineering.

It is intended to be used by coders, developers, technically-skilled traders, data scientists, and financial analysts for building trading algorithms.

CCXT was included as a dependency in the requirements.txt file so it should already be installed locally so let's go and ahead and import it.

from dotenv import load_dotenv
import os, json, time, ccxt

load_dotenv()  # Take environment variables from .env

After importing ccxt, we want to create an exchange object so we'll append this line to the end of the script.

binance = ccxt.binance({
    'apiKey': os.getenv('API_KEY'),
    'secret': os.getenv('API_SECRET'),
})

All we've done is instantiate a CCXT object and we've given it our keys as environment variables so we can connect to our account through the object we just created.

To test this out, let's retrieve our balance. Add this to the end of the bot.

portfolio = binance.fetch_balance() # This returns a dictionary of the assets in your portfolio
print(json.dumps(portfolio, indent=4))

After adding that, execute the program by running this command on the terminal:

$ python3 app.py

This should print out a long list of assets on the terminal in a structured format, you can find out more about the CCXT docs to see other cool stuff you could do with it.

Opening and Closing Orders

We're going to now attempt to buy crypto via the CCXT object, we'll simply be buying Solana (SOL) and then selling it 30 seconds later so we can see our code in action. Subsequent articles will show how to use indicators and even how to host a trading system on a server but for now, we'll keep things simple.

Add this to app.py

SOL_USDT = binance.markets['SOL/USDT']  # This returns the binance solana market object
#print(json.dumps(SOL_USDT, indent=4))

try:
    margin = portfolio["USDT"]["free"]
    # This gets the free USDT in your account

    amount = margin / binance.fetchTicker("SOL/USDT")["last"]
    # This computes the amount of SOL you can buy with the free USDT based on the last price

    amount = float(binance.amount_to_precision("SOL/USDT", amount))
    # This converts the calculated amount to appropriate amount of decimals accepted by the exchange

    if amount < SOL_USDT["limits"]["amount"]["min"]:
        print("Cannot place order, Not up to minimum tradeable amount")

    else:
        order = binance.create_order("SOL/USDT", 'market', 'buy', amount)
        if order:
            print(f"Successfully purchased {amount} of SOL")

except Exception as E:
    print(f"Error encountered: {str(E)}")
    # Simply checking any errors that might have occurred in the try block

Congrats! You just purchased crypto algorithmically. Alright, let's try to sell back the SOL after 10 seconds.

So add this final portion to the script

# Simply checking any errors that might have occurred in the try block

time.sleep(10)

try:
    margin = portfolio["SOL"]["free"]
    amount = float(binance.amount_to_precision("SOL/USDT", margin))

    if amount < SOL_USDT["limits"]["amount"]["min"]:
        print("Cannot place order, Not up to minimum tradeable amount")

    else:
        order = binance.create_order("SOL/USDT", 'market', 'sell', amount)
        if order:
            print(f"Successfully sold {amount} of SOL")

except Exception as E:
    print(f"Error encountered when selling: {str(E)}")
    # Simply checking any errors that might have occurred in the try block

Here's the GitHub repo to the above code and here's a screenshot of the entire code.

code.png

This bot doesn't do much now but in the next article, I'll be showing how to execute trades based on the signal of a technical indicator.

Thanks for sticking to the end and I'll see you in the next article.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐