def __init__(self): super().__init__() self.set_param("backtest", required=True, default=False) self.set_param("currencies", default=['BTC']) self.initial_price = -1 self.initial_funds = 0 self.funds = 0 self.positions = {} """ It's best to set up the backtesting position tracker locally because there's delay if I send trades to another module to handle tracking mock positions. Because of that, I might as well include the CBP client here too. """ if self.params['backtest']: self.initial_funds = 10000 self.funds = self.initial_funds for c in self.params['currencies']: self.positions[c] = { "price": -1, "size": 0 } else: # This part is not really supported yet. with open('./cbp-creds.txt', 'r') as f: api = f.readline() self._KEY = api[api.find('=')+1:].strip() secret = f.readline() self._SECRET = secret[secret.find('=')+1:].strip() passphrase = f.readline() self._PASSPHRASE = passphrase[passphrase.find('=')+1:].strip() self.client = cbp.AuthenticatedClient( key=self._KEY, secret=self._SECRET, passphrase=self._PASSPHRASE ) # init list of states, replace each one and train in batches self.init_model() self.action = tf.random.uniform(shape=(1,1), minval=0, maxval=2, dtype=tf.int32, seed=10)
def get_product_details(currency_id): print('CURRENCY ID', currency_id) user = get_user(session.get('username')) cb_client = cbp.PublicClient() cb_auth = cbp.AuthenticatedClient(key=cb_public_key, secret=cb_private_key, passphrase=cb_passphrase) accounts = cb_auth.get_accounts() account_id = None pub_currency = None for acc in accounts: if currency_id in acc['currency']: account_id = acc['id'] pub_currency = acc['currency'] + '-USD' print('PUB CURRENCY', pub_currency) try: product_resp = cb_auth.get_account(account_id) account_hist = cb_auth.get_account_history(account_id) acc_hist = list(account_hist) market_resp = cb_client.get_product_ticker(pub_currency) fills = cb_auth.get_fills(pub_currency) fills_lst = list(fills) except: return redirect(url_for('market_bp.market_index')) if request.method == 'POST': currency = pub_currency user_currency = UserCurrency.query.filter_by( user_id=user.id).filter_by(currency=currency).first() print(user_currency) db.session.delete(user_currency) db.session.commit() flash('{} removed from dashboard'.format(currency)) return redirect(url_for('market_bp.market_index')) return render_template('product_details.html', product=product_resp, market=market_resp, hist=acc_hist, fills=fills_lst)
import numpy as np import requests import json import time import sys from requests.auth import AuthBase import coinbasepro as cbp import sqlite3 coinbase_key = "" coinbase_passphrase = "" coinbase_secret = "" client = cbp.AuthenticatedClient(key=coinbase_key, secret=coinbase_secret, passphrase=coinbase_passphrase) #Function receives price of Ethereum def getPrice(): newData = client.get_product_ticker(product_id='ETH-USD') currentPrice = newData['price'] return float(currentPrice) #Function receives Ethereum balance def getETHbalance():
return request # api_url = 'https://api.pro.coinbase.com/' # auth = CoinbaseExchangeAuth(os.environ['CB_PUBLIC_KEY'], os.environ['CB_PRIVATE_KEY'], os.environ['CB_PASSPHRASE']) # # # Get accounts # r = requests.get(api_url + 'accounts', auth=auth) # print(r.json()) # # [{"id": "a1b2c3d4", "balance":... # Place an order # order = { # 'size': 1.0, # 'price': 1.0, # 'side': 'buy', # 'product_id': 'BTC-USD', # } # r = requests.post(api_url + 'orders', json=order, auth=auth) # print(r.json()) cb_passphrase = os.environ.get('CB_PASSPHRASE') cb_public_key = os.environ.get('CB_PUBLIC_KEY') cb_private_key = os.environ.get('CB_PRIVATE_KEY') cb_auth = cbp.AuthenticatedClient(key=cb_public_key, secret=cb_private_key, passphrase=cb_passphrase) print(dir(cb_auth))
def backfill_coinbasepro(api_key: str, api_secret: str, api_passphrase: str): conn = connect_serenity_db() cur = conn.cursor() type_code_cache = TypeCodeCache(cur) instrument_cache = InstrumentCache(cur, type_code_cache) exch_service = ExchangeEntityService(cur, type_code_cache, instrument_cache) auth_client = coinbasepro.AuthenticatedClient(key=api_key, secret=api_secret, passphrase=api_passphrase) # Coinbase Pro has a notion of account per currency for tracking balances, so we want to pull # out what it calls the profile, which is the parent exchange account profile_set = set() for account in auth_client.get_accounts(): profile_set.add(account['profile_id']) exchange = type_code_cache.get_by_code(Exchange, "CoinbasePro") account_by_profile_id = {} for profile in profile_set: account = exch_service.get_or_create_account( ExchangeAccount(0, exchange, profile)) account_by_profile_id[profile] = account # load up all the orders for order in auth_client.get_orders(status=['done']): order_uuid = order['id'] # market orders have no price if 'price' in order: price = order['price'] else: price = None # market orders that specify "funds" have no size if 'size' in order: size = order['size'] else: size = order['filled_size'] exchange_account = account_by_profile_id[order['profile_id']] instrument_type = type_code_cache.get_by_code(InstrumentType, 'CurrencyPair') instrument = instrument_cache.get_or_create_instrument( order['product_id'], instrument_type) exchange_instrument = instrument_cache.get_or_create_exchange_instrument( order['product_id'], instrument, exchange.get_type_code()) side = type_code_cache.get_by_code(Side, order['side'].capitalize()) if order['type'] is None: order['type'] = 'Market' order_type = type_code_cache.get_by_code(OrderType, order['type'].capitalize()) if 'time_in_force' in order: tif = type_code_cache.get_by_code(TimeInForce, order['time_in_force']) else: tif = type_code_cache.get_by_code(TimeInForce, 'Day') create_time = order['created_at'] order = ExchangeOrder(0, exchange, exchange_instrument, order_type, exchange_account, side, tif, order_uuid, price, size, create_time) exch_service.get_or_create_exchange_order(order) conn.commit() # load up all the fills, linking back to the orders for product in ['BTC-USD', 'ETH-BTC']: for fill in auth_client.get_fills(product_id=product): order_id = fill['order_id'] trade_id = fill['trade_id'] price = fill['price'] size = fill['size'] fees = fill['fee'] create_time = fill['created_at'] order = exch_service.get_entity_by_ak( ExchangeOrder, (exchange.get_type_code(), order_id)) fill = ExchangeFill(0, price, size, fees, trade_id, create_time) fill.set_order(order) exch_service.get_or_create_exchange_fill(fill) conn.commit()
api_settings = general_settings.api() schedule_settings = general_settings.schedule() for api in api_settings: key = api['Key'] b64secret = api['Secret'] passphrase = api['Passphrase'] apiurl = api['API-URL'] for the_schedule in schedule_settings: run_day = the_schedule['Day'] run_time = the_schedule['Time'] repeat_time = the_schedule['Repeat-Time'] run_every = the_schedule['Scheduled-Run'] auth_client = coinbasepro.AuthenticatedClient(key, b64secret, passphrase, api_url=apiurl) def check_funds(currency): account_data = auth_client.get_accounts() for account in account_data: if account['currency'] == currency: currency_balance = math.floor(account['balance']) return currency_balance def get_funding_account(fund_amount, currency, fund_source): if fund_source == "default": payment_methods = auth_client.get_payment_methods() for payment in payment_methods: if payment['primary_buy'] == True: payment_id = payment['id'] elif fund_source == "coinbase":
def get_auth_client(): cb_auth = cbp.AuthenticatedClient(key=cb_public_key, secret=cb_private_key, passphrase=cb_passphrase) return cb_auth