class CoinbaseConnector(selery_utils.Connector):
    def __init__(self, token, secret):
        super(CoinbaseConnector, self).__init__()
        self.client = Client(token, secret)
        self.account = self.client.get_primary_account()
        self.addresses = self.account.get_addresses()

    def pastTransactions(self):
        return self.client.get_transactions(self.account.id)

    def iswalletAddress(self, tocheck):
        for wallet in self.addresses['data']:
            if wallet['address'] == tocheck:
                return True
        return False

    def payout(self, target_email, target_amount, skip_notifications, description):
        tx = self.account.send_money(
            to=target_email, amount=float(target_amount), currency='btc', skip_notification=['false', 'true'][skip_notifications], description=description)
        return tx

    def balancecheck(self):
        amount = self.account['native_balance']['amount']
        currency = self.account['native_balance']['currency']
        return amount, currency

    def useremail(self):
        user = self.client.get_current_user()
        email = user['email']
        return email 
Exemplo n.º 2
0
class Trader(threading.Thread):
    def __init__(self, api_key, api_secret, alpha=0.5):
        assert 0 < alpha <= 1.0  # smoothing factor for the exponential moving avg function
        super(threading.Thread, self).__init__()
        self.alpha = alpha
        self.client = Client(api_key, api_secret)
        self.user = self.client.get_current_user()
        self.buys = []
        self.sells = []
        print 'Trading As:         %s (%s)' % (self.user['name'], self.user['email'])
        print 'Starting Balance:   $%s (%s BTC @ $%s/BTC)' % (self.balance['USD'], self.balance['BTC'], self.get_price())

    @property
    def account(self):
        return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0]

    @property
    def balance(self):
        return {
            self.account['balance']['currency']:        float(self.account['balance']['amount']),
            self.account['native_balance']['currency']: float(self.account['native_balance']['amount']),
        }

    def get_price(self):
        return float(self.client.get_spot_price()['amount'])

    def buy(self, amount):
        buy_obj = self.account.buy(amount, 'USD')
        self.buys.append(buy_obj)

    def sell(self, amount):
        sell_obj = self.account.sell(amount, 'USD')
        self.sells.append(sell_obj)

    def analyze(self):
        for idx, buy in enumerate(self.buys):
            if self.get_price() > buy['price'] + market_fees + min_profit_margin:
                self.buys.pop(idx)
                self.sell(buy['amount'])    # if price rises above buy price + market fees by a certain amount, sell early and reap the tiny profits
            elif self.get_price() < buy['price']:
                self.buys.pop(idx)
                self.sell(buy['amount'])    # if price drops below the price it was bought at, sell immediately to minimize losses
            else:
                pass                        # do nothing until the price fluctuates enough to make more of a difference

        for idx, sell in enumerate(self.sells):
            if self.get_price() > sell['price']:
                self.sells.pop(idx)
                self.buy(sell['amount'])    # if price starts to rise above the amount we sold it for, rebuy the same amount
            else:
                # if market trends downwards we'll lose (number of transactions * (market fee per transaction + min profit margin))
                pass                        # price is below the amount we sold for, don't do anything until it's passing break-even again


    def run(self):
        self.keep_running = True
        while self.keep_running:
            self.analyze()
Exemplo n.º 3
0
 def new_from_config(conf):
     attempt_load = True
     while attempt_load:
         attempt_load = False
         if conf.data.coinbase_api_key and conf.data.coinbase_api_secret:
             try:
                 print(colored("Attempting to load API key", "blue"))
                 client = Client(conf.data.coinbase_api_key,
                                 conf.data.coinbase_api_secret)
                 coinbase_user = client.get_current_user()
                 print("API Key Info:")
                 print("Name: " + colored(coinbase_user.name, "blue"))
                 print("Email: " + colored(coinbase_user.email, "blue"))
                 print("Country: " +
                       colored(coinbase_user.country.name, "blue"))
                 if coinbase_user.tiers.completed_description == 'Level 3':
                     print(
                         "Verification: " +
                         colored(coinbase_user.tiers.completed_description,
                                 "green"))
                 else:
                     print("Verification: " + colored(
                         coinbase_user.tiers.completed_description, "red"))
                     print(
                         colored("You must complete ", "cyan") +
                         colored("Level 3", "yellow") + colored(
                             " account verification at https://coinbase.com.",
                             "cyan"))
                 print("Do you want to proceed using this account?")
                 print(
                     colored("Type ", "cyan") + colored("yes", "yellow") +
                     colored(" and press ENTER to confirm.\n", "cyan") +
                     colored("Type ", "cyan") + colored("no", "yellow") +
                     colored(
                         " and press ENTER to be prompted "
                         "for a different API key.", "cyan"))
                 user_prompt = input("Confirm (yes/no): ")
                 user_prompt = user_prompt.lower()
                 if user_prompt[:1] == "y":
                     return client
             except Exception as e:
                 print(
                     colored(
                         "The previously stored API Key or API Secret is invalid",
                         "red"))
                 print(colored(e, "cyan"))
                 delete_api_key = input(
                     "Delete stored API key and API Secret? (yes/no): ")
                 delete_api_key = delete_api_key.lower()
                 if delete_api_key[:1] == "y":
                     conf.delete('coinbase_api_key')
                     conf.delete('coinbase_api_secret')
                     return
                 else:
                     attempt_load = True
Exemplo n.º 4
0
class CoinbaseConnector(selery_utils.Connector):
    def __init__(self, token, secret):
        super(CoinbaseConnector, self).__init__()
        self.client = Client(token, secret)
        self.account = self.client.get_primary_account()
        self.addresses = self.account.get_addresses()

    def pastTransactions(self):
        return self.client.get_transactions(self.account.id)

    def iswalletAddress(self, tocheck):
        for wallet in self.addresses["data"]:
            if wallet["address"] == tocheck:
                return True
        return False

    def payout(self, target_email, target_amount, skip_notifications,
               description):
        tx = self.account.send_money(
            to=target_email,
            amount=float(target_amount),
            currency="btc",
            skip_notification=["false", "true"][skip_notifications],
            description=description,
        )
        return tx

    def balancecheck(self):
        amount = self.account["balance"]["amount"]
        currency = self.account["balance"]["currency"]
        return amount, currency

    def native_balancecheck(self):
        native_amount = self.account["native_balance"]["amount"]
        native_currency = self.account["native_balance"]["currency"]
        return native_amount, native_currency

    def useremail(self):
        user = self.client.get_current_user()
        email = user["email"]
        return email
Exemplo n.º 5
0
 def new_from_prompt(conf):
     client = None
     while not client:
         coinbase_api_key = input('Enter API Key: ')
         coinbase_api_secret = input('Enter API Secret: ')
         print(chr(27) + "[2J" + chr(27) + "[H")  # Clear Screen
         try:
             client = Client(coinbase_api_key, coinbase_api_secret)
             coinbase_user = client.get_current_user()
             print("API Key Info:")
             print("Name: " + colored(coinbase_user.name, "blue"))
             print("Email: " + colored(coinbase_user.email, "blue"))
             print("Country: " +
                   colored(coinbase_user.country.name, "blue"))
             print("Do you want to proceed using this account?")
             print(
                 colored("Type ", "cyan") + colored("yes", "yellow") +
                 colored(" and press ENTER to confirm.\n", "cyan") +
                 colored("Type ", "cyan") + colored("no", "yellow") +
                 colored(
                     " and press ENTER to be prompted "
                     "for a different API key.", "cyan"))
             user_prompt = input("Confirm (yes/no): ")
             user_prompt = user_prompt.lower()
             if user_prompt[:1] != "y":
                 print(
                     colored(
                         "Discarding the API KEY and API Secret "
                         "you entered, starting over...", "red"))
             else:
                 conf.set('coinbase_api_key', coinbase_api_key)
                 conf.set('coinbase_api_secret', coinbase_api_secret)
                 return client
         except Exception as e:
             print(
                 colored("The API Key or API Secret you entered is invalid",
                         "red"))
             print(colored(e, "cyan"))
             print("Try again...")
Exemplo n.º 6
0
class MyClient(Endpoint):
    client = None
    connected = False

    API_VERSION = '2018-01-16'

    def __init__(self):
        self.FILE_NAME = 'cb_client.json'
        try:
            clientDict = Endpoint.read_json(self)
        except IOError as err:
            APIKey = ''
            while len(APIKey) == 0:
                APIKey = input('Please enter your API Key:')

            APISecret = ''
            while len(APISecret) == 0:
                APISecret = input('Please enter your API Secret:')

            clientDict = {'APIKey': APIKey, 'APISecret': APISecret}
            Endpoint.write_json(self, clientDict)
            clientDict = Endpoint.read_json(self)

        self.client = Client(clientDict['APIKey'],
                             clientDict['APISecret'],
                             api_version=self.API_VERSION)

        try:
            user = self.client.get_current_user()
        except APIError as err:
            print('Unable to communicate with coinbase User API.')
            print('Error: ' + err.message)
            os.remove(Endpoint.FILE_NAME)
        else:
            self.connected = True
            print('API Connection Successful.')
Exemplo n.º 7
0
def get_user_from_client(api_key, api_token):
    """Get the user name from Coinbase API credentials."""
    client = Client(api_key, api_token)
    user = client.get_current_user()
    return user
Exemplo n.º 8
0
import json
from os import getenv
from time import sleep
from dotenv import load_dotenv
from coinbase.wallet.client import Client

# Load environment constants
load_dotenv()
API_KEY = getenv("API_KEY")
API_SECRET = getenv("API_SECRET")
BTC_BURST_AMOUNT = float(getenv("BTC_BURST_AMOUNT"))
BTC_BURST_MINUTES = float(getenv("BTC_BURST_MINUTES"))

# Authenticate with Coinbase
client = Client(API_KEY, API_SECRET)
user = client.get_current_user()
print("Logged into Coinbase as {}".format(user.name))

# Get accounts
# (assuming only one account exists)
accounts = client.get_accounts()
for account in accounts.data:
    if account.currency == "USD":
        payout_method = account.id
        print("Loaded USD payout account, currently holding ${}".format(
            account.balance.amount))
    elif account.currency == "BTC":
        btc_account = account
        print("Loaded BTC account with {} BTC worth {} {}".format(
            account.balance.amount, account.native_balance.amount,
            account.native_balance.currency))
Exemplo n.º 9
0
class CoinBaseClient:
    def __init__(self):
        self.client = None
        self.user = None
        self.accounts = None
        self.buyList = []
        self.sellList = []
        self.transactionList = []
        # self.Connect()
        self.InitialiseData()

    def Connect(self):
        self.client = Client(API_KEY, API_SECRET)

    def InitialiseData(self):
        with open(BUYLIST_DATA_JSON_PATH_, 'r+') as bP:
            self.buyList = Serializer.deserialize(bP.read())
        # self.getBuys()
        # self.getTransactions()
        # self.getCurrentUser()

    def getCurrentUser(self):
        if self.user is None:
            self.user = self.client.get_current_user()
        return self.user

    def getBuys(self):
        with open(BUYLIST_DATA_JSON_PATH_, 'rb') as bP:
            self.buyList.__dict__ = Serializer.deserialize(bP.read())
        if self.buyList is None or len(self.buyList) == 0:
            for account in self.getAccounts():
                buys = self.client.get_buys(account.id)['data']
                crypto = CryptoBuyInfo()
                for buy in buys:
                    tx = Transaction(str(buy.id), float(buy.subtotal.amount),
                                     float(buy.amount.amount),
                                     parser.parse(buy.payout_at),
                                     buy.amount.currency,
                                     float(buy.fees[0].amount.amount),
                                     self.getPrice(buy.amount.currency, 'AUD'))
                    crypto.append(tx)

                self.buyList.append(crypto)
            json_str = Serializer.serialize(self.buyList)
            with open(BUYLIST_DATA_JSON_PATH_, 'wb') as b:
                b.write(json_str)

    def getTransactions(self):
        if len(self.transactionList) == 0:
            for account in self.getAccounts():
                self.transactionList.append(
                    self.client.get_transactions(account.id)['data'])
        # return self.transactionList

    def getSells(self):
        return self.client.get_sells(self.user.id)

    def getAccounts(self):
        if self.accounts is None:
            self.accounts = self.client.get_accounts()['data']
        return self.accounts

    def getPrice(self, currency, nativeCurrency):
        currencyPair = str(currency + '-' + nativeCurrency)
        response = requests.get('https://api.coinbase.com/v2/prices/' +
                                currencyPair + '/sell')
        return float(
            json.loads(response.content.decode("utf-8"))['data']['amount'])
Exemplo n.º 10
0
 def test_get_current_user(self):
     client = Client(api_key, api_secret)
     user = client.get_current_user()
     self.assertIsInstance(user, CurrentUser)
     self.assertEqual(user, mock_item)
Exemplo n.º 11
0
 def test_get_current_user(self):
   client = Client(api_key, api_secret)
   user = client.get_current_user()
   self.assertIsInstance(user, CurrentUser)
   self.assertEqual(user, mock_item)
Exemplo n.º 12
0
'''
- Coinbase: Secure online platform for buying, selling, transferring, and storing digital currency.
- Coinbase URL: https://www.coinbase.com/
- Reference: https://github.com/coinbase/coinbase-python
# Signup Coinbase account to get API key & Secret-> https://www.coinbase.com/

- Install Coinbase Python Module in CMD or Terminal.
>>> pip install coinbase --upgrade
'''

from coinbase.wallet.client import Client
print("\n *** CoinBase Using Python *** \n")
api_key = input(' Enter API Key : ')
api_secret = input(' Enter API Secret : ')
client = Client(api_key, api_secret)
print('\n Current User information : {}'.format(client.get_current_user()))
print('\n Coinbase Accounts Information : {}'.format(client.get_accounts()))
print('\n Coinbase Primary Account Information : {}'.format(client.get_primary_account()))
print('\n Get supported native currencies : {}'.format(client.get_currencies()))
print('\n Get exchange rates : {}'.format(client.get_exchange_rates()))
print('\n Buy Prices : {}'.format(client.get_buy_price(currency_pair = 'BTC-USD')))
print('\n Sell Price : {}'.format(client.get_sell_price(currency_pair = 'BTC-USD')))
print('\n Spot Price : {}'.format(client.get_spot_price(currency_pair = 'BTC-USD')))
print('\n Current Server Time : {}'.format(client.get_time()))
print('\n Get Authorization Information: {}'.format(client.get_auth_info()))
print('\n Get Transaction : {}'.format(account.get_transactions()))
print('\n Get Reports : {}'.format(client.get_reports()))
print('\n Get Buys : {}'.format(account.get_buys()))
print('\n Get Sells : {}'.format(account.get_sells()))
print('\n Get Sells: {}'.format(account.get_deposits()))
print('\n Get Withdrawls : {}'.format(account.get_withdrawals()))