コード例 #1
0
def connectAndGetPrimaryAccount():
  from coinbase.wallet.client import Client

  SANDBOX_URL = 'https://api.sandbox.coinbase.com'
  client = Client(API_KEY, API_SECRET,
                  base_api_uri=SANDBOX_URL)

  print "\nGet your primary coinbase account:", 
  primary_account = client.get_primary_account()
  print type(primary_account), primary_account["id"]
  
  return primary_account
コード例 #2
0
pdb.set_trace()

client = Client(api_key, api_secret, base_api_uri=SANDBOX_URL)

accounts = client.get_accounts()

print('accounts:', accounts)

for account in accounts.data:
    balance = account.balance
    print("%s: %s %s" % (account.name, balance.amount, balance.currency))
    print(account.get_transactions())

account = client.create_account(name="New Wallet")
balance = account.balance
print("%s: %s %s" % (account.name, balance.amount, balance.currency))

primary_account = client.get_primary_account()
address = account.create_address()

primary_account.send_money(to=address.address,
                           amount='0.01',
                           currency='BTC',
                           description='For being awesome!')

print(primary_account.get_transactions()[-1])

primary_account.refresh()
balance = primary_account.balance
print("%s: %s %s" % (primary_account.name, balance.amount, balance.currency))
コード例 #3
0
class Coinbase(Client):
    random_api_key = random_data.etc.password(length=5)
    random_api_secret = random_data.etc.password(length=5)
    """
    Доступные методы:
        price
        address_balance
    """
    def __init__(self,
                 api_key: str = random_api_key,
                 api_secret: str = random_api_secret):
        super().__init__(api_key, api_secret)  # Наследуем класс coinbase
        self.__client = Client(api_key, api_secret)
        self.__account_id = self.__client.get_primary_account()["id"]

    @property
    def client(self):
        return self.__client

    @property
    def account_id(self):
        return self.__account_id

    def price(self, currency="USD"):
        currency_pair = "BTC-{}".format(currency.upper())
        price = self.client.get_buy_price(currency_pair=currency_pair)
        return float(price["amount"])

    def address_balance(self, address_id, confirmations=1):
        balance = 0

        data = self.client.get_address_transactions(self.__account_id,
                                                    address_id)
        transactions = data["data"]

        if 0 < len(transactions):
            for transaction in transactions:
                hash = transaction["network"]["hash"]  # Txid
                transaction_sum = float(
                    transaction["amount"]
                    ["amount"])  # Сумма транзакции в виде 0.001 btc

                if 3 <= confirmations:
                    """
                    Если нужно 3 или больше подтверждений сети,
                    то проверяется транзакция на coinbase
                    """
                    if self.__check_confirmation_from_coinbase(transaction):
                        balance += transaction_sum

                elif confirmations in [1, 2]:
                    """
                    Если нужно 2 или 3 конфирма
                    """
                    transaction_info = blockcypher.get_transaction_details(
                        hash)

                    if "confirmations" in transaction_info:
                        transaction_confirmations = transaction_info[
                            "confirmations"]

                    elif self.__check_confirmation_from_coinbase(transaction):
                        transaction_confirmations = 3

                    else:
                        transaction_confirmations = 0

                    if confirmations <= transaction_confirmations:
                        balance += transaction_sum

                elif 0 == confirmations:
                    balance += transaction_sum

        return balance

    def __check_confirmation_from_coinbase(self, transaction, balance):
        if "confirmed" == transaction["network"]["status"]:
            response = True
        else:
            response = False

        return response
コード例 #4
0
 def test_get_primary_account(self):
     client = Client(api_key, api_secret)
     account = client.get_primary_account()
     self.assertIsInstance(account, Account)
     self.assertEqual(account, mock_item)
コード例 #5
0
ファイル: test_client.py プロジェクト: chuyqa/coinbase-python
 def test_get_primary_account(self):
   client = Client(api_key, api_secret)
   account = client.get_primary_account()
   self.assertIsInstance(account, Account)
   self.assertEqual(account, mock_item)
コード例 #6
0
class Coin():
    """
    """
    def __init__(self):
        API_KEY = os.getenv('COINBASE_API_KEY', False)
        API_SECRET = os.getenv('COINBASE_API_SECRET', False)
        self.client = Client(API_KEY, API_SECRET)
        self.primary_account = self.client.get_primary_account()

    def list_accounts(self):
        accounts = self.client.get_accounts()
        for account in accounts.data:
            balance = account.balance
            print('{0}: {1} {2}'.format(account.name, balance.amount, balance.currency))
            print(account.get_transactions)

    def create_account(self, wallet_name):
        account = self.client.create_account(name=wallet_name)
        balance = account.balance
        print('{0}: {1} {2}'.format(account.name, balance.amount, balance.currency))

    def create_order(self):
        metadata = dict()
        metadata['name'] = 'Joe Doe'
        metadata['email'] = '*****@*****.**'
        metadata['shipping_address'] = '123 5th Avenue, Portland OR 97171'
        order = self.client.create_order(amount='0.00000108', currency='BTC', name='Order #0108', description='Awesome energy bar', metadata=metadata)
        self.generate_qrcode(order.bitcoin_uri)
        print(order)
        return order

    def generate_qrcode(self, uri):
        img = qrcode.make(uri)
        img.save('out.png')

    def get_order(self, order_id):
        order = self.client.get_order(order_id)
        print(order)

    def list_orders(self):
        orders = self.client.get_orders().data
        for order in orders:
            print(json.dumps(order))
            # print('{0}: {1} {2} {3} {4}'.format(order.id, order.created_at, order.status, order.bitcoin_amount, order.name))

    def receive_money(self):
        address = self.primary_account.create_address()
        print(address)

    def request_money(self):
        self.primary_account.request_money(to="*****@*****.**", amount="1", currency="BTC")

    def get_account_balance(self):
        balance = self.primary_account.balance
        print(balance)

    def list_transactions(self):
        transactions = self.primary_account.get_transactions().data
        for transaction in transactions:
            print('{0} {1}: {2} {3} {4}'.format(transaction.id, transaction.created_at, transaction.type, transaction.amount, transaction.status))

    def get_latest_transaction(self):
        transactions = self.primary_account.get_transactions().data
        if len(transactions):
            transaction = transactions[-1]
            print('{0} {1}: {2} {3} {4}'.format(transaction.id, transaction.created_at, transaction.type, transaction.amount, transaction.status))

    def list_notifications(self):
        print(self.client.get_notifications())
コード例 #7
0
- 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()))
print('\n Get Orders : {}'.format(client.get_orders()))
print('\n Get Checkouts : {}'.format(client.get_checkouts()))
コード例 #8
0
ファイル: coinbasetest.py プロジェクト: MaxFangX/Tipster
    api_secret,
    base_api_uri=SANDBOX_URL)

accounts = client.get_accounts()

print('accounts:', accounts)

for account in accounts.data:
  balance = account.balance
  print("%s: %s %s" % (account.name, balance.amount, balance.currency))
  print(account.get_transactions())

account = client.create_account(name="New Wallet")
balance = account.balance
print("%s: %s %s" % (account.name, balance.amount, balance.currency))

primary_account = client.get_primary_account()
address = account.create_address()

primary_account.send_money(
    to=address.address,
    amount='0.01',
    currency='BTC',
    description='For being awesome!')

print(primary_account.get_transactions()[-1])

primary_account.refresh()
balance = primary_account.balance
print("%s: %s %s" % (primary_account.name, balance.amount, balance.currency))
コード例 #9
0
def bitcoin_moving_average_historical():
    items = {}
    day_to_day_bc_price = []
    day_to_day_bc_sell = []
    day_to_day_bc_buy = []
    buy_day_price = []
    sell_day_price = []
    days = []
    coinbase_key = os.environ['COINBASE_API_KEY']
    coinbase_secret = os.environ['COINBASE_API_SECRET']
    print(coinbase_key)
    print(coinbase_secret)
    client = Client(coinbase_key, coinbase_secret)
    account = client.get_primary_account()
    total = 0
    count = 0
    averagePrice = 0
    dayEstimate = 0
    currentPrice = client.get_buy_price(currency_pair='BTC-USD')
    currentPrice = currentPrice.get("amount")
    #If this is too large it'll throw 404
    time_to_track = 500
    today = datetime.today().date()
    print("this is today: " + str(today))
    end = today - timedelta(days=time_to_track)
    print("this is end: " + str(end))
    "Coindesk API get request to query legacy information on day scale"
    r = requests.get(
        "https://api.coindesk.com/v1/bpi/historical/close.json?start=" +
        str(end) + "&end=" + str(today) + "")
    print("this is response: " + str(r))
    dates = r.json()['bpi'][str(end)]
    print("this is the date:" + str(dates))
    buy_limit = 20
    buy = 0
    sell = 0
    coin = 0
    profit = 0
    bank = 2000
    n = 50
    total_for_n = 0
    days_from_start = 0
    while (end != today):
        days.append(end)
        price = r.json()['bpi'][str(end)]
        day_to_day_bc_price.append(price)
        if days_from_start >= n:
            front_window_price = r.json()['bpi'][str(end - timedelta(days=n))]
            # print("yikes: "+str(front_window_price))
            average = total_for_n / n
            # print("this is n: "+str(n))
            total_for_n = total_for_n - front_window_price
            # print("running_average_n: "+str(total_for_n))
            # print("running average: "+str(average))
            if average > price:
                buy = buy + 1
                coin = coin + price / (price - buy_limit)
                profit = profit - buy_limit
                bank = bank - buy_limit
                day_to_day_bc_buy.append(end)
                buy_day_price.append(price)
                if profit > 0:
                    print("price: " + str(price))
                    print("buy profit: " + str(profit))
            elif average < price and coin > 0:
                sell = sell + 1
                coin = coin - price / (price - buy_limit)
                profit = profit + buy_limit
                bank = bank + buy_limit
                day_to_day_bc_sell.append(end)
                sell_day_price.append(price)
                if profit > 0:
                    print("price: " + str(price))
                    print("sell profit: " + str(profit))
        total_for_n = total_for_n + price
        end = end + timedelta(days=1)
        days_from_start = days_from_start + 1
    print("this is the profit using this algorithm: " + str(profit))
    print("coins bought: " + str(coin))
    print("coins value: " +
          str(coin * r.json()['bpi'][str(today - timedelta(days=1))]))
    print("total over all value: " +
          str(profit +
              (coin * r.json()['bpi'][str(today - timedelta(days=1))])))
    print("bank: " + str(bank))
    print("sell: " + str(sell))
    print("buy: " + str(buy))
    items = {
        "prices": day_to_day_bc_price,
        "days": days,
        "buy": day_to_day_bc_buy,
        "buy_day_prices": buy_day_price,
        "sell": day_to_day_bc_sell,
        "sell_day_prices": sell_day_price
    }
    return items
コード例 #10
0
# Imports
import config  #Remove this in PowerBI
import pandas as pd
from coinbase.wallet.client import Client

# Variables
api_key = config.api_key  #Replace 'config.api_key' with your APIkey
api_secret = config.api_secret  #Replace 'config.api_secret' with your APIsecret
endpoint = 'accounts'  #Choose betweeen 'accounts', 'transactions', 'buys', 'sells'

#Connect
client = Client(api_key, api_secret)

#Account ID List
input_accountid = [client.get_accounts()][0]['data']
accountid_array = [client.get_primary_account()['id']]
for item in input_accountid:
    accountid = item.id
    accountid_array.append(accountid)

# Get endpoint data
input_data = []

if endpoint == 'accounts':
    input_primary = [client.get_primary_account()][0]
    input_data.append(input_primary)
    for item in input_accountid:
        input_item = item
        input_data.append(input_item)

else:
コード例 #11
0
#       - add your api key in the api_key variable
#       - add your api secretin the api_secret variable


from coinbase.wallet.client import Client
import os

os.system("clear")

api_key = ""        # insert your api key here
api_secret = ""     # insert your api secret here

client = Client(api_key, api_secret)
time = client.get_time().iso
user = client.get_current_user()
balance = client.get_primary_account().balance

print("+------------------------------------------------+")
print("| Coinbase Bitcoin Manager v1.0                  |")
print("+------------------------------------------------+")
print
print("Server time: %s " % time)
print("Name: %s " % user.name)
print("Primary Wallet Balance: %s " % balance)
print("--------------------------------------------------")
buy = client.get_buy_price(currency_pair = 'BTC-USD')
print("BTC Buy Price: %s " % buy)
sale = client.get_sell_price(currency_pair = 'BTC-USD')
print("BTC Sales Price: %s " % sale)
print("--------------------------------------------------")