def __init__(self, minute_model, api_key, secret_key, passphrase, minute_len=30,
                 prediction_ticker='ETH', bitinfo_list=None, is_sandbox_api=True):

        temp1 = "2018-05-05 00:00:00 EST"
        temp2 = "2018-06-05 00:00:00 EST"

        self.price_model = CryptoPriceModel(temp1, temp2, forecast_offset=minute_len, prediction_ticker=prediction_ticker,
                                            sym_list=bitinfo_list, time_units='min', model_path=minute_model)
        self.bitinfo_list = bitinfo_list
        self.minute_length = minute_len
        self.prediction_ticker = prediction_ticker.upper()
        self.prediction = None
        self.price = None

        self.product_id = prediction_ticker.upper() + '-USD'
        self.save_str = 'most_recent' + str(self.price_model.prediction_length) + 'currency_' + self.prediction_ticker + '.h5'

        if is_sandbox_api:
            self.api_base = 'https://api-public.sandbox.pro.coinbase.com'
            self.auth_client = cbpro.AuthenticatedClient(api_key, secret_key, passphrase, api_url=self.api_base)
        else:
            self.api_base = 'https://api.pro.coinbase.com'
            self.auth_client = cbpro.AuthenticatedClient(api_key, secret_key, passphrase, api_url=self.api_base)

        data = {'Market': 100, 'Algorithm': 100}
        current_datetime = current_est_time()
        self.returns = pd.DataFrame(data=data, index=[current_datetime])
def setapi(key, secret, passp):
    auth_client = cbpro.AuthenticatedClient(
        key,
        secret,
        passp,
        api_url="https://api-public.sandbox.pro.coinbase.com")
    return auth_client
Exemple #3
0
def get_private_client(credentials):
    """Returns the cbpro AuthenticatedClient using the credentials from the parameters dict"""
    private_client = cbpro.AuthenticatedClient(credentials['KEY'],
                                               credentials['SECRET'],
                                               credentials['PASSPHRASE'],
                                               api_url=credentials['URL'])
    return private_client
Exemple #4
0
    def __init__(self, ticker, time, live_data, do_trade):
        '''
        Constructor
        '''
        #self.GRANULARITY = (60,300,900,3600, 21600, 86400)
        self.GRANULARITY = [60]

        self.ticker = ticker
        self.live_data = live_data
        self.do_trade = do_trade

        # self.future_df = self.getFuture()
        # inialize future as empty dataframe but we might not need it
        self.future_df = pd.DataFrame()

        # we need to connect even if data is not live
        self.login = Login()
        self.trade_client = cbpro.AuthenticatedClient(self.login.key,
                                                      self.login.b64secret,
                                                      self.login.passphrase)

        if (live_data):

            self.virtual_time = datetime.datetime.utcnow().replace(
                microsecond=0, second=0)

        else:

            self.virtual_time = time
            # data is not live, get from file
            file = r'../data/coinbase_BTC_master.csv'
            self.file_data = FileDataReader(file)
Exemple #5
0
 def __init__(self, API_KEY, SECRET_KEY, PASSPHRASE):
     self.API_KEY = API_KEY
     self.SECRET_KEY = SECRET_KEY
     self.PASSPHRASE = PASSPHRASE
     self.auth_client = cbpro.AuthenticatedClient(API_KEY, SECRET_KEY,
                                                  PASSPHRASE)
     self.public_client = cbpro.PublicClient()
def get_currency_balance(currency, key, secret, passphrase):
    auth_client = cbpro.AuthenticatedClient(key, secret, passphrase)
    response = auth_client.get_accounts()
    for item in response:
        if item['currency'] == currency:
            output = float(item['available'])
    return output
Exemple #7
0
def on_open(ws):
    global coin_client, sheet
    print("Connected")

    scope = [
        'https://www.googleapis.com/auth/spreadsheets',
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/drive"
    ]

    try:
        creds = ServiceAccountCredentials.from_json_keyfile_name(
            'Sheets API Key.env', scope)
    except:
        print("error here")
    client = gspread.authorize(creds)

    sheet = client.open('Bitcoin').worksheet("50-100 sma")

    url = "https://api-public.sandbox.pro.coinbase.com"

    coin_client = cbpro.AuthenticatedClient(os.getenv("API"),
                                            os.getenv("API_SECRET"),
                                            os.getenv("PASSPHRASE"),
                                            api_url=url)

    send_data = {
        "type": "subscribe",
        "channels": [{
            "name": "ticker",
            "product_ids": ["BTC-USD"]
        }]
    }

    ws.send(json.dumps(send_data))
Exemple #8
0
 def __init__(self, key: str, passphrase: str, b64secret: str):
     '''
         init CoinbaseProStats by using an api key, passphrase, and secret which can be created 
         at this link -> https://pro.coinbase.com/profile/api 
     '''
     self.auth_client = cbpro.AuthenticatedClient(key, b64secret,
                                                  passphrase)
Exemple #9
0
    def init_engine_and_indicators(self):
        self.initializing = True
        try:
            self.cbpro_websocket.close()
        except:
            pass
        # Periods to update indicators for
        self.indicator_period_list = []
        # Periods to actively trade on (typically 1 per product)
        self.trade_period_list = {}
        # List of products that we are actually monitoring
        self.product_list = set()
        fiat_currency = self.config['fiat']
        if self.config['sandbox']:
            api_url = "https://api-public.sandbox.pro.coinbase.com"
        else:
            api_url = "https://api.pro.coinbase.com"
        auth_client = cbpro.AuthenticatedClient(self.config['key'],
                                                self.config['secret'],
                                                self.config['passphrase'],
                                                api_url=api_url)

        for cur_period in self.config['periods']:
            self.logger.debug("INITIALIZING %s", cur_period['name'])
            if cur_period.get('meta'):
                new_period = period.MetaPeriod(
                    period_size=(60 * cur_period['length']),
                    fiat=fiat_currency,
                    product=cur_period['product'],
                    name=cur_period['name'],
                    cbpro_client=auth_client)
            else:
                new_period = period.Period(period_size=(60 *
                                                        cur_period['length']),
                                           product=cur_period['product'],
                                           name=cur_period['name'],
                                           cbpro_client=auth_client)
            self.indicator_period_list.append(new_period)
            self.product_list.add(cur_period['product'])
            if cur_period['trade']:
                if self.trade_period_list.get(cur_period['product']) is None:
                    self.trade_period_list[cur_period['product']] = []
                self.trade_period_list[cur_period['product']].append(
                    new_period)
        max_slippage = Decimal(str(self.config['max_slippage']))
        self.trade_engine = engine.TradeEngine(auth_client,
                                               product_list=self.product_list,
                                               fiat=fiat_currency,
                                               is_live=self.config['live'],
                                               max_slippage=max_slippage)
        self.cbpro_websocket = engine.TradeAndHeartbeatWebsocket(
            fiat=fiat_currency, sandbox=self.config['sandbox'])
        self.cbpro_websocket.start()
        self.indicator_period_list[0].verbose_heartbeat = True
        self.indicator_subsys = indicators.IndicatorSubsystem(
            self.indicator_period_list)
        self.last_indicator_update = time.time()

        self.init_interface()
        self.initializing = False
Exemple #10
0
def get_cb_client(client_type,
                  key=None,
                  secret=None,
                  passphrase=None,
                  api_url="https://api.pro.coinbase.com"):
    """

    :param client_type:
    :param key:
    :param secret:
    :param passphrase:
    :param api_url:
    :return:
    usage:
    >>> key='1b19ba867bf0e06f93f583b88825d485'
    >>> secret = 'TKCdKrstN+eX7KKZAhG08rPCh3Yo7kMcf9CUXEaE9TlQ/HAOzXely9UkdVv4PdVUtieW8eP97I9kXd0d4I2AGQ=='
    >>> passphrase = 'uihizupz01'
    >>> api_url = 'https://api.pro.coinbase.com'
    >>> client = get_cb_client('private', key, secret, passphrase)
    """
    if client_type == 'public':
        client = cbpro.PublicClient()
    else:
        client = cbpro.AuthenticatedClient(key,
                                           secret,
                                           passphrase,
                                           api_url=api_url)
    return client
def client():
    """Client that connects to sandbox API. Relies on authentication information
    provided in api_config.json"""
    with open('api_config.json') as file:
        api_config = json.load(file)
    c = cbpro.AuthenticatedClient(
        api_url='https://api-public.sandbox.pro.coinbase.com', **api_config)

    # Set up account with deposits and orders. Do this by depositing from
    # the Coinbase USD wallet, which has a fixed value of > $10,000.
    #
    # Only deposit if the balance is below some nominal amount. The
    # exchange seems to freak out if you run up your account balance.
    coinbase_accounts = c.get_coinbase_accounts()
    account_info = [x for x in coinbase_accounts
                    if x['name'] == 'USD Wallet'][0]
    account_usd = account_info['id']
    if float(account_info['balance']) < 70000:
        c.coinbase_deposit(10000, 'USD', account_usd)
    # Place some orders to generate history
    c.place_limit_order('BTC-USD', 'buy', 1, 0.01)
    c.place_limit_order('BTC-USD', 'buy', 2, 0.01)
    c.place_limit_order('BTC-USD', 'buy', 3, 0.01)

    return c
    def __init__(self,
                 api_key,
                 secret_key,
                 passphrase,
                 sym_list,
                 base_currency='USD',
                 offset_value=70,
                 is_sandbox=False):
        self.wallets = {}

        if is_sandbox:
            api_base = 'https://api-public.sandbox.pro.coinbase.com'
            auth_client = cbpro.AuthenticatedClient(api_key,
                                                    secret_key,
                                                    passphrase,
                                                    api_url=api_base)
            sleep(PRIVATE_SLEEP)
            pub_client = cbpro.PublicClient(api_url=api_base)
        else:
            auth_client = cbpro.AuthenticatedClient(api_key, secret_key,
                                                    passphrase)
            sleep(PRIVATE_SLEEP)
            pub_client = cbpro.PublicClient()

        self.auth = auth_client

        for product_id in sym_list:
            # The base can be put in the symbols in the format Quote-Base for use with multiple currencies
            if (type(base_currency) is list) or (type(base_currency) is tuple):
                product_dat = product_id.split('-')
                symbol = product_dat[0]
                base = product_dat[1]
                if base not in base_currency:
                    continue
            else:
                symbol = product_id
                base = base_currency
            self.wallets[product_id] = Wallet(api_key,
                                              secret_key,
                                              passphrase,
                                              base=base,
                                              sym=symbol,
                                              auth_client=auth_client,
                                              pub_client=pub_client)
            self.wallets[product_id].offset_value = offset_value

        self.symbols = sym_list
Exemple #13
0
 def __init__(self, key, b64secret, passphrase):
     self.url = "https://api.pro.coinbase.com"
     self.auth_client = cbpro.AuthenticatedClient(key, b64secret,
                                                  passphrase)
     self.public_client = cbpro.PublicClient()
     self.account_data_w_balance = []
     self.instrument_list = []
     self.set_account_data()
Exemple #14
0
def api():
    key = "ENTER_KEY"
    secret = "ENTER_SECRET"
    password = "******"
    auth_client = cbpro.AuthenticatedClient(key, secret, password)
    data = auth_client.get_product_ticker('COIN-USDC OR COIN-USD')
    current = (data['price'])
    return current
Exemple #15
0
 def authenticate(self) -> cbpro.AuthenticatedClient:
     key = self.config['auth'].get('key')
     passphrase = self.config['auth'].get('passphrase')
     b64secret = self.config['auth'].get('b64secret')
     auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)
     assert 'message' not in auth_client.get_accounts(
     ), 'Auth credentials are invalid.'
     return auth_client
def check_order_status(response, key, secret, passphrase):
    auth_client = cbpro.AuthenticatedClient(key, secret, passphrase)
    order_id = response['id']
    output = True
    if order_id is not None:
        check = auth_client.get_order(order_id)
        output = check['settled']
    return output
Exemple #17
0
def setup_client(config):
    global client
    client = cbpro.AuthenticatedClient(config['system']['api_key'],
                                       config['system']['secret_key'],
                                       config['system']['passphrase'],
                                       api_url=config['system']['uri'])
    setup_api_timeout()
    return client
Exemple #18
0
def api():
    key = "ENTER_CB_KEY"
    secret = "ENTER_CB_SECRET"
    password = "******"
    auth_client = cbpro.AuthenticatedClient(key, secret, password)
    # change below pair to coin wanted, most are COIN-USD or COIN-USDC
    data = auth_client.get_product_ticker('BTC-USD')
    current = (data['price'])
    return float(current)
def print_cbpro_funding_accounts(requests):

    cbpro_api = cbpro.AuthenticatedClient(cbpro_apikey,
                                          cbpro_secret,
                                          cbpro_passphrase)

    for funding_account in cbpro_api.get_payment_methods():
        print('the id number for {} is: {}'.format(funding_account['name'],
              funding_account['id']))
Exemple #20
0
	def __init__(self):
		self.folder = "./log_cbpro/"

		self._public_client = cbpro.PublicClient()

		self._key = os.getenv("API_KEY_SANDBOX")
		self._b64secret = os.getenv("API_SECRET_SANDBOX")
		self._passphrase = os.getenv("API_PASSPHRASE_SANDBOX")

		self._auth_client = cbpro.AuthenticatedClient(self._key, self._b64secret, self._passphrase, api_url="https://api-public.sandbox.pro.coinbase.com")
    def __init__(self,
                 api_key,
                 secret_key,
                 passphrase,
                 prediction_ticker='ETH',
                 is_sandbox_api=False,
                 auth_client=None,
                 pub_client=None,
                 base_ticker='USD'):

        self.product_id = prediction_ticker.upper() + '-' + base_ticker
        if not (base_ticker == 'USD'):
            prediction_ticker = self.product_id
        self.orders = {'buy': {}, 'sell': {}}
        self.usd_decimal_num = EXCHANGE_CONSTANTS[prediction_ticker][
            'resolution']
        self.usd_res = 10**(-self.usd_decimal_num)
        self.quote_order_min = QUOTE_ORDER_MIN
        self.base_order_min = EXCHANGE_CONSTANTS[prediction_ticker][
            'base order min']
        self.base_decimal_num = EXCHANGE_CONSTANTS[prediction_ticker][
            'base resolution']
        self.crypto_res = 10**(-self.base_decimal_num)
        self.filt_fills = None
        self.all_fills = None
        self.order_book = None
        self.filtered_fill_times = None
        self.fill_time = 0

        if auth_client is None:
            if is_sandbox_api:
                self.api_base = 'https://api-public.sandbox.pro.coinbase.com'
                self.auth_client = cbpro.AuthenticatedClient(
                    api_key, secret_key, passphrase, api_url=self.api_base)
                self.pub_client = cbpro.PublicClient(api_url=self.api_base)
            else:
                self.auth_client = cbpro.AuthenticatedClient(
                    api_key, secret_key, passphrase)
                self.pub_client = cbpro.PublicClient()
        else:
            self.auth_client = auth_client
            self.pub_client = pub_client
Exemple #22
0
 def apiauth(self):
     #Auth / APIs
     auth = tweepy.OAuthHandler('xxXXXXXXXXXXXxx', 'xxXXXXXXXXXXXxx')
     auth.set_access_token('xxXXXXXXXXXXXxx', 'xxXXXXXXXXXXXxx')
     twitter_api = tweepy.API(auth) # Twitter
     crypto_api = cryptonator.Cryptonator() # crypto price API
     b64secret = 'xxXXXXXXXXXXXxx'
     key = 'xxXXXXXXXXXXXxx'
     passphrase = 'xxXXXXXXXXXXXxx'
     auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase) # CoinbasePro
     return twitter_api, auth_client
def make_trade(pair, amount, trade_type, key, secret, passphrase):
    auth_client = cbpro.AuthenticatedClient(key, secret, passphrase)
    if trade_type == 'buy':
        response = auth_client.buy(order_type='market',
                                   product_id=pair,
                                   funds=amount)
    if trade_type == 'sell':
        response = auth_client.sell(order_type='market',
                                    product_id=pair,
                                    size=amount)
    return response
Exemple #24
0
def buy(name):

    auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)

    balance = get_balance("USD-USD")

    print(
        auth_client.buy(
            funds=balance,  #USD
            order_type='market',
            product_id=name))
Exemple #25
0
def sell(name):

    auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)

    balance = get_balance(name)

    print(
        auth_client.sell(
            size=balance,  #USD
            order_type='market',
            product_id=name))
def print_cbpro_funding_accounts(requests):

    cbpro_apiurl = "https://api-public.sandbox.pro.coinbase.com" if cbpro_sandbox else "https://api.pro.coinbase.com/"
    cbpro_api = cbpro.AuthenticatedClient(cbpro_apikey,
                                          cbpro_secret,
                                          cbpro_passphrase,
                                          api_url=cbpro_apiurl)

    for funding_account in cbpro_api.get_payment_methods():
        print('the id number for {} is: {}'.format(funding_account['name'],
                                                   funding_account['id']))
Exemple #27
0
 def __init__(self,
              logs_to_cloud=False,
              use_real_money=(getenv('USE_REAL_MONEY') == 'YES')):
     self.logs = Logs(name="trading", to_cloud=logs_to_cloud)
     self.cb_public = cbpro.PublicClient()
     self.cb_stream = CBWebsocketClient
     if use_real_money:
         key = getenv('CB_PROD_KEY')
         b64secret = getenv('CB_PROD_B64SECRET')
         passphrase = getenv('CB_PROD_PASSPHRASE')
         self.coinbase = cbpro.AuthenticatedClient(key, b64secret,
                                                   passphrase)
     else:
         key = getenv('CB_SANDBOX_KEY')
         b64secret = getenv('CB_SANDBOX_B64SECRET')
         passphrase = getenv('CB_SANDBOX_PASSPHRASE')
         self.coinbase = cbpro.AuthenticatedClient(
             key,
             b64secret,
             passphrase,
             api_url="https://api-public.sandbox.pro.coinbase.com")
Exemple #28
0
def main():

	keys = []
	for line in sys.stdin:
		keys.append(line.strip())
	
	key = keys[0]
	secret = keys[1]
	passphrase = keys[2]

	auth_client = cbpro.AuthenticatedClient(key,secret,passphrase)

	print(getCurrentPrice(auth_client, 'BTC-USDT', 300))
 def __init__(self,
              API_KEY,
              API_SECRET,
              API_PASS,
              ENV_URL="https://api-public.sandbox.pro.coinbase.com"):
     self.API_KEY = API_KEY
     self.API_SECRET = API_SECRET
     self.API_PASS = API_PASS
     self.ENV_URL = ENV_URL
     self.client = cbpro.AuthenticatedClient(self.API_KEY,
                                             self.API_SECRET,
                                             self.API_PASS,
                                             api_url=self.ENV_URL)
    def __init__(self, keys, balance=0, currencies=None):
        self.client = cbp.AuthenticatedClient(keys["API_KEY"], keys["SECRET"],
                                              keys["PHRASE"])

        self.balance = balance

        if currencies is None:
            self.currencies = {}
        else:
            self.currencies = currencies

        self.starting_value = self.get_account_value()
        self.account_value = self.starting_value