Implement this simple BTC-USD trend following algorithm today, using Coinbase Pro API and python
Here is a simple algorithm you can implement immediately for BTC-USD, using the Coinbase Pro API and python. This is just a jumping-off point (but includes ideas for improvement in the future).
Clone repo here: https://github.com/samchaaa/simple_btc_algo
Here’s what to do to get started
git clone https://github.com/samchaaa/simple_btc_algo.git
Step 2.) Open
btc_algo.py and replace credentials for
secret from your Coinbase Pro account. Make sure your API key is authorized for view and trades.
Step 3.) Run
Here’s how it works
We’ve modified the function
AuthenticatedClient to include
stop_price, in case you want to place stop orders.
The strategy lives in
btc_algo.py and is very simple, clocking in at 100 lines.
PublicClient and calls
get_product_historic_rates() to get the last 100 hourly bars. It returns either
False (whether the 50 period average > 100 period average).
AuthenticatedClient (for getting account information and placing trades). It can check your balances (BTC or USD) and place orders (buy or sell).
run() initializes Account, then checks if it is the top of the hour with
If so, we call
History().signal, requesting the hourly data and returning a signal.
auth_client.is_balanceUSD() checks if there is USD available to buy. Vice versa if it is a sell.
After each hourly check, we call
time.sleep((60*60) — datetime.now().minute*60 — (datetime.now().microsecond/1000000)) to sleep until the top of the next hour (including microseconds, so we don’t sleep longer and longer each loop).
This algo is a very quick way to get involved today. However it is not perfectly optimized. Here are some ideas for improvement:
cron: Using cron could make the algo cleaner and more robust to termination.
Managing data: Instead of calling historic rates once per hour, we could call 100 hours up front, then call just the last hour every time we want to check for a signal. We would pop the oldest hour, append the latest hour, and check for our signal. This would save time calling the Coinbase API for 100 hours instead of 1 hour.
Don’t check balance: Ignore checking the balance… just send the trade request. If you don’t have a balance (either of USD or BTC), the trade doesn’t go through anyway.
Interested in more ready-to-implement code, backtests, and algorithmic trading ideas? Subscribe to samchaaa++ here.