Nowadays, you can always find a helpful package for almost anything, including for automating your financial strategies! But for some, there’s always that splinter in your mind regarding the security behind a package/wrapper, especially when it comes to one’s money. So instead of relying on someone else’s work, why not code it ourselves!
The Code While it would be beneficial to understand how a website communicates with a user, for this exercise, I will be going directly into the code, giving a bit of an overview regarding certain topics. So as always, to start us off, we need to import the packages we will be using.
import requests #Requests and JSON are used to help us communicate import json #with the website import time #Time is needed for out timestamps import hashlib #These three help us create a signature to import hmac #authenticate our requests to the website import base64 from requests.auth import AuthBase #Helps us combine all our info #so we can send it out From here, we will need to use or create our API keys from Coinbase. To create these keys, please give this very helpful article a view.
A quick reminder, the API Key/Secret/Passphrase are unique to you, please do not share it with other people since it will allow them to use your account. For extra security, add your IP to your “Allowed/Whitelist” in the API settings.
Next, we will be creating our string variable for the URL we will be using.
url = "https://api.pro.coinbase.com" Our next step, would be to create our secure application to the Coinbase API. For this, we need to use our API information, a timestamp, and our signature and to send this application to the website, we need AuthBase, a helpful command to handle authentications for us. Following this Coinbase’s developers guide, we start making our own authenticator.
class API_Auth(AuthBase): def call(self, r): timestamp = str(time.time())
message = ''.join([timestamp, r.method,
r.path_url, (r.body or '')])
message = message.encode('ascii')
hmac_secret = base64.b64decode(api_secret)
signature = hmac.new(hmac_secret, message, hashlib.sha256) signature_b64 = base64.b64encode(signature.digest()).decode('utf-8')
r.headers.update( {
"Accept": "application/json",
'Content-Type': 'Application/JSON',
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': api_key,
'CB-ACCESS-PASSPHRASE': api_passphrase
})
return r We start out by making a class, which will help us with each request we make, and add a function to it. Our timestamp variable lets us create a timestamp for each time we make a request. The message variable combines our timestamp, request method (POST or GET), specific URL, and our body, which is the collection of information (i.e. ticker, size, funds, type of order, etc.) we send to the website when we make an order. Hmac_secret grabs our API secret key and decodes it from binary to something needed for our request. The signature variable combines our hmac_secret, message variables and encodes our message with SHA-256. While in the original guide from Coinbase, this was the only thing needed, but when I attempted the same method, I would keep getting an invalid signature response. After searching around, I found that we need to pass the signature variable and do an encode/decode for it to work properly, which is why we need the signature_b64 variable. Lastly, we just create our headers, which include our API information and we should be good to go!
Get Luis Morales’s stories in your inbox Join Medium for free to get updates from this writer.
Enter your email Subscribe From here, we just go ahead and create some functions that will help us get some information and to create some orders. First, I would like to get the bid/ask prices of a crypto currency, in my case, LTC.
def bid_price(ticker): #Ticker variable is a string auth = API_Auth() bid = requests.get(url+'/products/' + ticker + '/ticker', auth=auth) bid_response = json.loads(bid.text) bid_price = bid_response['bid'] return bid_price To get the ticker information, such as LTC-USD, we go ahead and send a request to the specified URL. Don’t forget that we already specified our URL earlier, but now we just need to complete the URL for what we need it for, which in this case, is to obtain ticker information as we can see in the bid variable. We then apply our bid variable as a JSON object, as seen in the bid_response variable, and if we check our response, we should see something like this.
{'trade_id': #######, 'price': '105.07', 'size': '0.33158025', 'time': '#############', 'bid': '105.02', 'ask': '105.07', 'volume': '181184.66196811'} Seeing that I only want the bid price, we create a bid_price variable and we should only get the price. We can then just create another function, but for ask pricing, by just changing bid_response[‘bid’] to bid_response[‘ask’].
Another function we can make that will be useful for our code, would be to get our balances.
def LTC_balance(): # To get all accounts, use: requests.get(url+'/accounts/', auth=auth)
ltc_id = "Your ID here"
auth = API_Auth()
account_response = requests.get(url+'/accounts/' + ltc_id, auth=auth)
account_info = json.loads(account_response.text)
balance = account_info['balance']
available = account_info['available']
info_string = 'Balance: ' + balance +' | ' + 'Available to Trade: ' + available
return info_string
It pretty much follows the same process as the pricing functions that we previously created, but with a bit of more involved. First, we need to get our ID that specifies our, in this case, LTC wallet. We can get all of our accounts by sending a request to the accounts URL, as shown by the comment in the second line of the code above. Once we have the wallet that we want, we can just go ahead and specify it in our ltc_id variable and this function will return our balance and available balance to trade.
Furthermore, and most importantly, we create our buy and sell functions. For our buy, we go ahead and create the following function.
def buy_LTC(usd):
usd = str(float(usd))
payload = {
"type": "market",
"side": "buy",
"product_id": "LTC-USD",
"funds": usd
}
auth = API_Auth()
order_response = requests.post(url+'/orders/', data = json.dumps(payload), auth=auth)
return order_response.text
For buying LTC, we are going to use our USD balance, which we can find by adjust our LTC_balance function, to buy some LTC. We need to make sure that the amount of USD we wish to buy, is in string format, hence our usd variable. The payload variable creates our order information, which follows this format created by Coinbase, so we can send it through a POST request. Once we complete our transaction, this function will display our order information. To sell LTC, we just change our payload to this.
ltc = str(float(ltc))
payload = {
"type": "market",
"side": "sell",
"product_id": "LTC-USD",
"size": ltc
}
So instead of using our USD balance, this time we will be using how many LTC we currently have available for trading.
And that’s pretty much it! Hopefully by the end of this article, a bit of how wrappers/APIs work, has been some what explained in a easy to follow code along. Using these functions, you can now set up your algorithm however you wish, such as buying LTC if you see a 10% price drop or maybe something a bit more complex, the world is now at your fingertips. If you need more information on what else you can do with Coinbase’s API, feel free to take a look at this website. And as always, thank you for taking the time to read this article and I wish you guys good luck on your Crypto adventure!