Created
July 13, 2018 15:18
-
-
Save dvdbng/0aa66f4cb84579b9726679845f9bffdf to your computer and use it in GitHub Desktop.
Coinbase pro DCA with limit orders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
import time | |
import base64 | |
import hmac | |
import hashlib | |
from decimal import Decimal, getcontext | |
API_URL = 'https://api.pro.coinbase.com' | |
PRODUCT = {'ETH-EUR': 45, 'BTC-EUR': 10} # What products to buy and how much fiat to spend on each | |
PRICE = Decimal(0.995) # What % of the bid price set limit orders to | |
API_KEY = os.environ["COINBASE_API_KEY"] | |
API_SECRET = os.environ["COINBASE_API_SECRET"] | |
API_PASSPHRASE = os.environ["COINBASE_API_PASSPHRASE"] | |
getcontext().prec = 6 | |
class CoinbaseExchangeAuth(requests.auth.AuthBase): | |
def __init__(self, api_key, secret_key, passphrase): | |
self.api_key = api_key | |
self.secret_key = secret_key | |
self.passphrase = passphrase | |
def __call__(self, request): | |
timestamp = str(time.time()) | |
message = timestamp + request.method + request.path_url + (request.body or '') | |
hmac_key = base64.b64decode(self.secret_key) | |
signature = hmac.new(hmac_key, message, hashlib.sha256) | |
signature_b64 = signature.digest().encode('base64').rstrip('\n') | |
request.headers.update({ | |
'CB-ACCESS-SIGN': signature_b64, | |
'CB-ACCESS-TIMESTAMP': timestamp, | |
'CB-ACCESS-KEY': self.api_key, | |
'CB-ACCESS-PASSPHRASE': self.passphrase, | |
'Content-Type': 'application/json' | |
}) | |
return request | |
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASSPHRASE) | |
def get_ticker(market): | |
r = requests.get('%s/products/%s/ticker' % (API_URL, market), auth=auth) | |
r.raise_for_status() | |
return r.json() | |
def post_order(market, amount, price): | |
order = dict( | |
product_id=market, | |
side='buy', | |
type='limit', | |
size=str(amount), | |
price=str(round(price, 2)), | |
post_only=True, | |
) | |
r = requests.post('%s/orders' % (API_URL), json=order, auth=auth) | |
if r.status_code != 200: | |
print(r.text) | |
r.raise_for_status() | |
return r.json() | |
def buy(market, amount): | |
bid_price = Decimal(get_ticker(market)['bid']) | |
buy_price = PRICE * bid_price | |
print(post_order(market, amount / buy_price, buy_price)) | |
for (market, amount) in PRODUCT.items(): | |
buy(market, amount) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment