Python Scripts for Crypto Trading Bots [API Trading Tutorial]

robot-1650649_1920.jpg

If you’ve been in the cryptocurrency market for more than a few days, you probably know the feeling of the market dropping and you feel hopeless in cashing out your portfolio into a stablecoin or Bitcoin.

Instead of panicking, take control of your portfolio by learning how to write powerful scripts which can instantly execute the trades you need to move in and out of positions.

By the end of this tutorial, you will be equipped with tools which allow you to fully automate and control your portfolio without ever logging into your exchange accounts.

Before we get started, take a few minutes to browse some of our previous tutorials. Each article discusses a unique aspect of trading bots which is important when building a robust strategy.

Trading through exchange APIs It only takes a few minutes to get set up with a script which can consolidate your portfolio, so let’s get started!

Install Trading Library

Every exchange has unique trading APIs. Integrating and managing multiple exchange APIs is a nightmarish experience, so we will use the Shrimpy Trading Library to manage all of these exchanges for us. This reduces our development time by a few years, so we can spend more time building our trading bots.

pip install shrimpy-python

Installing the library will take a moment, but once done we can go ahead and open our Python environment so we can begin scripting!

Import Trading Library

Before writing the meat of the script, start by importing the Shrimpy library.

import shrimpy

This will be the only library we need for now.

API Keys

Connecting to exchanges requires a one-time setup of APIs. There are two different sets of API keys we need to create: Exchange API keys and Shrimpy master keys.

Exchange API Keys

Exchange API keys can be accessed by logging into your preferred cryptocurrency exchange account. Once you log in, navigate to the section of the website which allows you to generate API keys.

Each exchange will allow you to control different permissions you provide for the individual key. In order to complete this tutorial, you will need to provide the API key with both the ability to read asset balances as well as trading. You do not need to give the key access to withdrawals.

After the keys are generated, securely store them in addition to using them in the following steps to trade using these keys. We must also create variables for the name of the exchange we are using, along with our public and secret keys.

exchange_name = 'bittrex'
exchange_public_key = 'fbnnn1xzimjustkeyboardmashing8xn1t8'
exchange_secret_key = '09672v4n09xn0morekeyboardmashing947'

You can find tutorials on how to create your API keys and what settings are required here. Ignore the steps about linking to Shrimpy, just enter the public and private key here instead.

Note: Shrimpy supports the following 16 different exchanges, which you can specify by replacing their name for “exchange_name”: binance, bittrex, bittrexinternational, kucoin, poloniex, bibox, huobi, hitbtc, bitstamp, bitfinex, coinbasepro, kraken, gemini, huobiglobal, bitmart, and okex.

Shrimpy Master Keys

In addition to the exchange API keys, we will need to generate our master keys for Shrimpy. These keys can be accessed by signing up for the Shrimpy developer APIs.

Upon signing up, you will see a page where you can create new master keys by selecting the “Create Api Master Key” button.

Before leaving the Shrimpy developer application after generating your keys, ensure you have enabled “User”, “Account”, and “Trading” permissions on your master keys. Without all three of these permissions, you will not be able to complete this tutorial.

Once updated with these permissions, save your keys in a safe location. In our script, we will assign them to a public and secret key variable to be used later in this tutorial.

shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'

Note: The Shrimpy Developer APIs cost $14 to manage up to 10 users. This gives you access to all of the trading features. Unlike some of our other tutorials, completing this tutorial will require at least the lowest subscription tier.

Create Client

We don’t have any more keys to generate, so continue the script by creating our Shrimpy client. This will allow us to communicate with the Shrimpy servers through the APIs.

client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

Create User

Before we can link any exchange accounts and start trading, we need to create a user. The purpose of users in Shrimpy is to provide a direct mapping from exchange accounts to users. Since exchange accounts are always owned by a real person, this allows us to create a simple structure where Shrimpy automatically relates users to their exchange accounts.

create_user_response = client.create_user('Satoshi Nakamoto')
user_id = create_user_response['id']

Link Exchange Account

Now that we have a user, we can link an exchange account to that user.

link_account_response = client.link_account(
    user_id,
    exchange_name,
    exchange_public_key,
    exchange_secret_key
)

account_id = link_account_response['id']

Note: In the Shrimpy developer APIs, it’s possible to create an unlimited number of users and link up to 20 exchange accounts to each user. In this tutorial, we will only create one user and link one exchange account. However, it would be easy to adjust the code to allow for multiple exchange accounts or users.

Get Account Balances

One of the first concerns with trading is knowing how much of each asset you have available on the exchange to trade. Shrimpy makes the process of collecting this data easy. Simply request balance data through the following call.

balance = client.get_balance(user_id, account_id)
holdings = balance['balances']

Pick Our Consolidation Asset

For this tutorial, we will be picking a single asset for which we will go all in. That means our script will sell every other asset in our portfolio and only buy this one asset.

Assign the asset you want to buy to a variable. This will be used in the following steps when trading.

consolidation_symbol = 'BTC'

Make Trades

Sell everything in our portfolio to buy the “consolidation symbol” asset.

Warning: Running this script to completion will execute trades on your exchange account. That is not a joke, you will literally sell everything in your portfolio to buy Bitcoin. We are not responsible for the misuse of this script, the trading fees you will be charged, or the funds you may lose as a result of using this script. Please be careful when constructing a trading strategy.

The purpose of this script is to provide a fun teaching example of how to trade on exchanges using APIs.

for asset in holdings:
    asset_symbol = asset['symbol']
    asset_amount = asset['nativeValue']
    if symbol != consolidation_symbol:
        print('Selling ' + str(asset_amount) + ' of ' + asset_symbol)
        create_trade_response = client.create_trade(
            user_id,
            account_id,
            asset_symbol,
            consolidation_symbol,
            asset_amount
        )

Done!

That wasn’t so bad now was it.

Without too much effort, we were able to build a script which connected to a cryptocurrency exchange, collected data regarding your current account balances, and trade everything to Bitcoin.

Note: You do not need to re-link your API keys and create a new user every time you want to trade. Once created, these things are securely stored on the Shrimpy servers to conveniently allow you to access them at any time.


Putting It All Together

Trading tutorial - cmd window.png

The following scripts detail everything we covered above. For convenience, two scripts have been provided. The first script is the complete script which should be run the first time. Each time after the original run, you can use the second script.

Warning: Again, these scripts will literally trade on your real cryptocurrency exchange account. Running these scripts means you fully understand that trades will be executed. We will not provide refunds for value that is lost due to trading.

# import required libraries
import shrimpy
import time

# assign your Shrimpy Master API keys for later use
shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'

# assign your exchange keys for which you wish to access the balance data
exchange_name = "bittrex"
exchange_public_key = 'fbnnn1xzimjustkeyboardmashing8xn1t8'
exchange_secret_key = '09672v4n09xn0morekeyboardmashing947'

# create the Shrimpy client
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

# create a user which will be linked to our exchange
create_user_response = client.create_user('The Shrimp Master')
user_id = create_user_response['id']

# link our first exchange so we can access balance data
link_account_response = client.link_account(
    user_id,
    exchange_name,
    exchange_public_key,
    exchange_secret_key
)

account_id = link_account_response['id']

# wait while Shrimpy collects data for the exchange account
# only required the first time linking
time.sleep(5)

# collect asset balances on the exchange
balance = client.get_balance(user_id, account_id)
holdings = balance['balances']

# select the asset for which you would like to consolidate
consolidation_symbol = 'BTC'

# sell every asset besides the consolidation asset
for asset in holdings:
    asset_symbol = asset['symbol']
    asset_amount = asset['nativeValue']
    if asset_symbol != consolidation_symbol:
        print('Selling ' + str(asset_amount) + ' of ' + asset_symbol)
        create_trade_response = client.create_trade(
            user_id,
            account_id,
            asset_symbol,
            consolidation_symbol,
            asset_amount
        )

Now that you have run the first script, you won’t need to connect your API keys or create another user to trade on the same exchange account. Of course, if you want to link multiple exchange accounts or create more users for people who will also use your service, then you can easily modify the code to create more users or link more exchange accounts based on your requirements.

Additional Runs

After the initial run, you can now run the following code to consolidate your funds on the same exchange account.

# import required libraries
import shrimpy

# input your user and account IDs
user_id = 'dc12349b-1234-12k4-123n12n12nnf'
account_id = 12345

# assign your Shrimpy Master API keys for later use
shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'

# create the Shrimpy client
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

# collect asset balances on the exchange
balance = client.get_balance(user_id, account_id)
holdings = balance['balances']

# select the asset for which you would like to consolidate
consolidation_symbol = 'BTC'

# sell every asset besides the consolidation asset
for asset in holdings:
    asset_symbol = asset['symbol']
    asset_amount = asset['nativeValue']
    if asset_symbol != consolidation_symbol:
        print('Selling ' + str(asset_amount) + ' of ' + asset_symbol)
        create_trade_response = client.create_trade(
            user_id,
            account_id,
            asset_symbol,
            consolidation_symbol,
            asset_amount
        )

Just like that, you now have a simple script which can consolidate your portfolio into a single asset. Whether the market is going up or down, this can be a useful tool for you to quickly move between positions.

Note: To understand how the trades will be executed, review the Shrimpy Developer API Docs before running any scripts.

Crypto Trading Bots

These scripts can provide the mental framework for developing more advanced trading bots. Whether you want to build a complex trading tool which offers countless strategies or just want a personal way to quickly move funds in your portfolio, these scripts can be a strong foundation for your journey.

Shrimpy is designed to help you scale. There are no limits on the number of users or trades you can execute with our developer APIs.

To keep up with our blog and YouTube series which will teach you how to build complete trading bots, don’t forget to join our developer telegram.

To access the complete Python and Node libraries, follow these links:

Node

Python

If you’re building something with the Shrimpy APIs, let us know! We would love to hear how we can continue to support you at every stage of your development.


About Shrimpy

Shrimpy leads the market as the premier portfolio management application. Users are able to configure a custom crypto portfolio and implement a passive rebalancing strategy, removing the hassle of having to actively trade crypto.

Shrimpy Web Application: Shrimpy - Cryptocurrency Portfolio Management

Shrimpy’s Developer Trading API is a unified way to integrating trading functionality across every major exchange. Collect historical market data, access real-time websockets, execute advanced trading strategies, and manage an unlimited number of users.

Shrimpy Crypto Trading API: Shrimpy | Crypto Trading APIs for Developers

Don’t forget to follow us on Twitter and Facebook for updates, and ask any questions to our amazing, active community on Telegram.

The Shrimpy Team