How to Begin Algorithmic Trading in Python – Ethan Bond
Coinbase is an exchange for cryptocurrencies, which means that all of the users on Coinbase are trading currencies with other users on Coinbase. You have the option to buy or sell cryptocurrencies with USD or other cryptocurrencies. When you buy or sell, it is called placing an order. There are three types of orders: limit, market, and stop. For this tutorial we will only be concerned with market orders, but you can read about the other types here. Market orders are the simplest type of order. You simply tell Coinbase you want X amount of a currency and you pay for it at whatever the current price is. Coinbase takes a fee which is (currently) equivalent to 0.25% of your order, per order. In the future I will write an article about how the market dynamic works, and how your purchases affect the price.
For this tutorial, we will be trading the cryptocurrency Bitcoin Cash on the exchange Coinbase Pro. In order to do this yourself, you will need a Coinbase pro account which you can get here.
Once you have a Coinbase Pro account, you will need to get an API key. To do this, log into your account, click on your name in the top right, and select the “API” tab from the drop-down. On the next page select the box that says +NEW API KEY
Make sure to select the “view” and “trade” permission boxes
Coinbase will give you an API key, API secret, and passphrase. Make sure to record all three and keep them safe.
To get started, you will need to have couple of libraries installed:
NumPy and cbpro.
These can be installed using the python package manager pip.
pip install numpy
pip install cbpro
The most important part of algotrading is the algorithm used. If you are planning to actually trade, most of your time should be spent on determining your strategy. There are many different types of strategies in algotrading. But for simplicity, we will just write a program that will aim to buy low and sell high based on a single indicator. An indicator is a commonly used calculation that uses price and volume to show strength, momentum, or a trend in the market. To experiment and play around with indicators, check out tradingview.com. For this tutorial, we will use an indicator called the Coppock Curve, which is normally used for crop futures, but will make for a good example with cryptocurrencies. Note that if we were algotrading for real, we would want to use more than one indicator.
The plan will be to buy at the bottom of the Coppock curve, when the slope goes from negative to positive. And then sell at the top of the Coppock curve, when the slope goes from positive to negative.
The file will work by repeatedly buying and selling when the conditions are met. The only way it will stop running is if you turn it off or the stop loss is activated, we will talk more about that later.
Create a new python file and import the two libraries we installed as well as time and datetime. Create variables with your API credentials, and create an auth_client object using the format below.
import numpy as np
import datetime as dt
import cbpro
import time# CB Pro granted api credentials as strings
apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
apiSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
passphrase = "XXXXXXXXXXX"auth_client = cbpro.AuthenticatedClient(apiKey,apiSecret,passphrase)
Next we will create some variables that will be needed for decisions later on.
# Amount to initially invest
initInvestment = 20.00# Amount that will be used for purchase starts at the initial amount
funding = initInvestment# Currency to trade, for reference:
# 'BCH-USD' = Bitcoin (BTC) Cash, 'BTC-USD' = Bitcoin (BTC), 'ETH-USD' = Ether
currency = 'BCH-USD'# Will return the ID of your specific currency account
def getSpecificAccount(cur):
x = auth_client.get_accounts()
for account in x:
if account['currency'] == cur:
return account['id']# Get the currency's specific ID
specificID = getSpecificAccount(currency[:3])# Granularity (in seconds). So 300 = data from every 5 min
period = 300# We will keep track of how many iterations our bot has done
iteration = 1# Start off by looking to buy
buy = True
Everything from here on out will be in a loop that will repeat every five minutes.
The next thing we need to do is pull in the latest price data from the Coinbase API. We do this by using the “get_product_historic_rates” function for the past data and the “get_product_ticker” function to get the price data at that instant.
try:
historicData = auth_client.get_product_historic_rates(currency, granularity=Period) # Make an array of the historic price data from the matrix
price = np.squeeze(np.asarray(np.matrix(historicData)[:,4])) # Wait for 1 second, to avoid API limit
time.sleep(1) # Get latest data and show to the user for reference
newData = auth_client.get_product_ticker(product_id=currency)
print(newData)
currentPrice=newData['price']except:
# In case something went wrong with cbpro
print("Error Encountered")
As mentioned above, we will use the Coppock Curve indicator. This indicator is created by taking the 10 interval moving average of the sum of the 11 and 14 interval rates of change. This isn’t an important part of this tutorial, so don’t worry if it is difficult to understand. The code below shows how we calculate the indicator values and derivatives.
# Calculate the rate of change 11 and 14 units back, then sum them
ROC11 = np.zeros(13)
ROC14 = np.zeros(13)
ROCSUM = np.zeros(13)for ii in range(0,13):
ROC11[ii] = (100*(price[ii]-price[ii+11]) / float(price[ii+11]))
ROC14[ii] = (100*(price[ii]price[ii+14]) / float(price[ii+14]))
ROCSUM[ii] = ( ROC11[ii] + ROC14[ii] )# Calculate the past 4 Coppock values with Weighted Moving Average
for ll in range(0,4):
coppock[ll] = (((1*ROCSUM[ll+9]) + (2*ROCSUM[ll+8]) + (3*ROCSUM[ll+7]) + (4*ROCSUM[ll+6]) + (5*ROCSUM[ll+5]) + (6*ROCSUM[ll+4]) + (7*ROCSUM[ll+3]) + (8*ROCSUM[ll+2]) + (9*ROCSUM[ll+1]) + (10*ROCSUM[ll])) / float(55))# Calculate the past 3 derivatives of the Coppock Curve
coppockD1 = np.zeros(3)
for mm in range(3):
coppockD1[mm] = coppock[mm] - coppock[mm+1]
Now that we have our indicator and are ready to buy or sell, we need to adjust our funding variables and create variables that will hold the amount of cryptocurrency owned.
# The maximum amount of crypto that can be purchased with your funds
possiblePurchase = (float(funding)) / float(currentPrice)# The amount of currency owned
owned = float(auth_client.get_account(specificID)['available'])# The value of the cryptocurrency in USD
possibleIncome = float(currentPrice) * owned
This is the most important part of the python script. As shown above, we will try to purchase at the bottom of the Coppock Curve, and sell at the top. To do this, we will use a conditional to check whether the derivatives of the curve are going from negative to positive or vice versa. We will place the order with Coinbase, and then update the funding/owned amounts appropriately.
# Buy Conditions: latest derivative is + and previous is -
if buy == True and (coppockD1[0]/abs(coppockD1[0])) == 1.0 and (coppockD1[1]/abs(coppockD1[1])) == -1.0: # Place the order
auth_client.place_market_order(product_id=currency, side='buy', funds=str(funding)) # Print message in the terminal for reference
message = "Buying Approximately " + str(possiblePurchase) + " " + currency + " Now @ " + str(currentPrice) + "/Coin. TOTAL = " + str(funding) print(message) # Update funding level and Buy variable
funding = 0
buy = False# Sell Conditions: latest derivative is - and previous is +
if buy == False and (coppockD1[0]/abs(coppockD1[0])) == -1.0 and (coppockD1[1]/abs(coppockD1[1])) == 1.0: # Place the order
auth_client.place_market_order(product_id=currency, side='sell', size=str(owned)) # Print message in the terminal for reference
message = "Selling " + str(owned) + " " + currency + "Now @ " + str(currentPrice) + "/Coin. TOTAL = " + str(possibleIncome) print(message) # Update funding level and Buy variable
funding = int(possibleIncome)
buy = True
A stop loss is a feature that will sell all of your securities and stop trading in the event that the price begins to drop significantly. It is good practice to add a stop loss anytime you are automating trading. Below is a stop loss that will activate if the amount of funding available to the bot is less that 80% of what it started with.
# Stop loss: sell everything and stop trading if your value is
# less than 80% of initial investment
if (possibleIncome+funding) <= 0.8 * initInvestment: # If there is any of the crypto owned, sell it all
if owned > 0.0:
auth_client.place_market_order(product_id = currency, side='sell', size = str(owned))
print("STOP LOSS SOLD ALL") # Will break out of the while loop and the program will end
break
Below is the complete code, available on GitHub
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
iteration number 1
Current Price: 308.02000000
Your Funds = 20.0
You Own 0.0 BCH
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
iteration number 2
Current Price: 308.34000000
Your Funds = 20.0
You Own 0.0 BCH
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
iteration number 3
Current Price: 309.52000000
Your Funds = 20.0
You Own 0.0 BCH
Published at Sun, 14 Jul 2019 18:36:54 +0000
Bitcoin Pic Of The Moment
By ▓▒░ TORLEY ░▒▓ on 2014-10-24 20:38:30
