def main(event, context):
    COINBASE_API_KEY = os.environ['COINBASE_API_KEY']
    COINBASE_API_SECRET = os.environ['COINBASE_API_SECRET']
    DYNAMODB_TABLE = os.environ['bitcoin_data_table']

    dynamodb_client = boto3.client('dynamodb')
    sns_client = boto3.client('sns')

    # Initialises coinbase client
    client = Client(COINBASE_API_KEY,
                    COINBASE_API_SECRET,
                    api_version='2017-12-30')

    btc_buy_price = client.get_buy_price(currency_pair='BTC-GBP')

    # Retrieves current time
    time = client.get_time()

    # Puts the item in the DynamoDB table
    data_put = dynamodb_client.put_item(TableName=DYNAMODB_TABLE,
                                        Item={
                                            'timestamp': {
                                                'S': time.iso
                                            },
                                            'btc_buy_price': {
                                                'S': btc_buy_price.amount
                                            }
                                        })

    return {"statusCode": 200}
class CoinbaseExchange():
    def __init__(self):
        self.CLIENT = Client(os.environ["Coinbase_API_Key"],
                             os.environ["Coinbase_API_Secret"])

    def get_balances(self):
        balances = []
        info = self.CLIENT.get_accounts()
        for asset in info['data']:
            if float(asset['balance']['amount']) != 0:
                balance = {
                    "amount": float(asset['balance']['amount']),
                    "currency": asset['balance']['currency']
                }
                balances.append(balance)
        return balances

    def get_Price(self, asset, currency):
        try:
            price_info = self.CLIENT.get_buy_price(
                currency_pair=f"{asset}-{currency}")
        except Exception as e:
            raise e
        else:
            price = float(price_info['amount'])
        return price
Beispiel #3
0
class CoinbaseManager(object):
    """Manager for the coinbase API"""
    def __init__(self):
        super(CoinbaseManager, self).__init__()
        self.api_key = os.environ.get('COINBASE_API_KEY')
        self.api_secret = os.environ.get('COINBASE_API_SECRET')
        self.client = Client(self.api_key, self.api_secret)

    def get_curreny_pair(self, crypto_currency, exchange_currency):
        """Return the currency pair to get the price from API"""
        currency_pair = '%s-%s' % (crypto_currency, exchange_currency)
        return currency_pair

    def get_spot_price(self, crypto_currency, exchange_currency):
        """Get the spot price from API"""
        currency_pair = self.get_curreny_pair(crypto_currency,
                                              exchange_currency)
        price = self.client.get_spot_price(currency_pair=currency_pair)
        return price.amount

    def get_buy_price(self, crypto_currency, exchange_currency):
        """Get the buy price from API"""
        currency_pair = self.get_curreny_pair(crypto_currency,
                                              exchange_currency)
        price = self.client.get_buy_price(currency_pair=currency_pair)
        return price.amount

    def get_sell_price(self, crypto_currency, exchange_currency):
        """Get the sell price from API"""
        currency_pair = self.get_curreny_pair(crypto_currency,
                                              exchange_currency)
        price = self.client.get_sell_price(currency_pair=currency_pair)
        return price.amount
Beispiel #4
0
class CoinbaseEx(Exchange):
    def __init__(self,
                 key=None,
                 secret=None,
                 currency_from="EUR",
                 currency_to="BTC"):
        super().__init__(currency_from, currency_to)

        self.exchange = Client(key, secret)
        self.exchange.apikey = key
        self.exchange.secret = secret

        self.set_buy_fees(variable=0.0149)
        self.set_sell_fees(variable=0.0149)

    def get_current_buy_rate(self):
        rates = self.exchange.get_buy_price(
            currency_pair="{}-{}".format(self.currency_from, self.currency_to))

        assert rates["base"] == self.currency_to
        assert rates["currency"] == self.currency_from

        return (float(rates["amount"]))

    def buy(self, amount, include_fees=True, execute=False):
        transaction = super().buy(amount, include_fees=include_fees)
        return (transaction)
Beispiel #5
0
def buy_bitcoin():
    connection = get_connection()
    client = Client('fakeapikey', 'fakeapisecret')
    buy_info = client.get_buy_price(currency_pair='BTC-USD')
    buy_price = float(buy_info["amount"])
    qty = request.form['qty']
    cmd = connection.cursor()
    cmd.execute("select remain_capital from trade_user where user_id = 1")
    remain = cmd.fetchmany(1)
    remain = float(remain[0][0])
    qty_float = float(qty)
    total_price = qty_float * buy_price
    if total_price <= remain:
        buy_price = str(buy_price)
        sql = 'insert into trade_record (quantity,item_id,price) values (' + qty + ',1,' + buy_price + ')'
        result = connection.cmd_query(sql)
        # insert the price to the database, the variable of price is buy_price

        remain = remain - total_price
        remain = str(remain)
        # update the reamin value to the MySQL database
        sql1 = 'update trade_user set remain_capital=' + remain + ' where user_id=1'
        result = connection.cmd_query(sql1)

        connection.commit()
        connection.close()
        return render_template('graph.html')
    else:
        return "有内鬼!"
 def actual(self):
     client = Client('https://api.coinbase.com/v2/currencies', '0')
     Result0 = client.get_buy_price()
     Result1 = client.get_sell_price()
     Result2 = client.get_spot_price()
     self._compra.setText(Result0.get('amount'))
     self._venta.setText(Result1.get('amount'))
     self._spot.setText(Result2.get('amount'))
Beispiel #7
0
def buy_btc(amount, addr):
  client = Client(api_key,api_secret)
  account = client.get_primary_account()
  payment_method = client.get_payment_methods()[0]
  buy_price  = client.get_buy_price(currency='USD')
  buy = account.buy(amount=amount/(buy_price*1.1),
                    currency="BTC",
                    payment_method=payment_method.id)
  tx = account.send_money(to=addr,
                                amount=amount/(buy_price*1.1),
                                currency='BTC')
def get_btc_buyprice():
    cointype = request.args.get("cointype", 'BTC')
    client = Client('apibuy', 'secretbuy')
    buy_btc = client.get_buy_price(currency_pair='{}-USD'.format(cointype))
    print(buy_btc)
    return_json = {
        'amount': float(buy_btc['amount']),
        'base': buy_btc['base'],
        'currency': buy_btc['currency']
    }
    return json.dumps(return_json)
def get_realtime_price(cointype, float_num=False):
    client = Client('apibuy', 'secretbuy')
    buy_btc = client.get_buy_price(currency_pair='{}-USD'.format(cointype))
    if not float_num:
        items = buy_btc['amount'].split('.')
        if len(items) == 2:
            price_int, price_decimal = items
        elif len(items) == 1:
            price_int, price_decimal = items[0], '00'
        else:
            price_int, price_decimal = '0', '00'
        return price_int, price_decimal
    else:
        return float(buy_btc['amount'])
Beispiel #10
0
def creat_bill_btc(chat_id, callback_id, message_id, sum, name_good, amount):
    #if dop.amount_of_goods(name_good) <= int(amount): bot.answer_callback_query(callback_query_id=callback_id, show_alert=True, text='Выберите меньшее число товаров к покупке')
    #el
    if dop.get_coinbasedata() == None:
        bot.answer_callback_query(
            callback_query_id=callback_id,
            show_alert=True,
            text='Принять деньги на btc кошелёк в данный момент невозможно!')
    else:
        api_key, api_secret = dop.get_coinbasedata()
        client = Client(api_key, api_secret)
        account_id = client.get_primary_account()['id']
        sum = int(sum) + 10  #прибавляется комиссия в btc
        btc_price = round(
            float((client.get_buy_price(currency_pair='BTC-RUB')["amount"])))
        print(btc_price)
        sum = float(str(sum /
                        btc_price)[:10])  #сколько сатох нужно юзеру оплатить
        address_for_tranz = client.create_address(account_id)[
            'address']  #получение кошелька для оплты

        with open(
                'https://drive.google.com/open?id=1F7UFARDfsTKih-tdJnXH6KlzikWfO9tz'
                + str(chat_id) + '.txt',
                'w',
                encoding='utf-8') as f:
            f.write(str(amount) + '\n')
            f.write(str(sum) + '\n')
            f.write(address_for_tranz)
        key = telebot.types.InlineKeyboardMarkup()
        key.add(
            telebot.types.InlineKeyboardButton(
                text='Проверить оплату', callback_data='Проверить оплату btc'))
        key.add(
            telebot.types.InlineKeyboardButton(
                text='Вернуться в начало', callback_data='Вернуться в начало'))
        try:
            bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text='Чтобы купить ' + name_good + ' количеством ' +
                str(amount) + '\nПереведите `' + str(sum) +
                '` btc на адрес `' + str(address_for_tranz) + '`',
                parse_mode='Markdown',
                reply_markup=key)
        except:
            pass
        he_client.append(chat_id)
Beispiel #11
0
    def OnToggle(self, event):
        client = Client("WNCJ3l6KlXgGDmqq", "Il6nr9t43HFinjYzIyKPF4eAMtNf1c67"
                        )  #update this to take values later
        state = event.GetEventObject().GetValue()
        #print(self.state)
        #rint("onnnd")
        #print(event.GetEventObject().GetValue())
        if state == True:
            #print(self.state)
            self.state = 1
            event.GetEventObject().SetLabel("Stop")  #change button text
            self.check_button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggleOff)
            while self.state == 1:
                time.sleep(1)
                price = float(
                    client.get_buy_price(currency_pair='BTC-USD')['amount'])
                #print(price)
                self.priceText.SetLabel(str(price))  #gotta turn it to a strong
                wx.Yield()

            else:
                event.GetEventObject().SetLabel("Start")
    def calculate_premium(self):

        # get coinbase price
        coinbase_monitor = Client(api_key='admin', api_secret='admin')
        coinbase_price = float(coinbase_monitor.get_buy_price()['amount'])
        print('BTC price in Coinbase:   %.2f USD' % coinbase_price)

        # get huobi price
        huobi_monitor = huobi_main_monitor.Huobi_Main_Monitor()
        huobi_price = float(huobi_monitor.get_btccny_bid_price())
        print('BTC price in Huobi:      %.2f CNY' % huobi_price)

        # get exchange rate
        exchange_rate = float(
            coinbase_monitor.get_exchange_rates()['rates']['CNY'])
        print('Exchange rate is now:    %.2f CNY/USD' % exchange_rate)

        # cal premium (huobi -> coinbase)
        premium = huobi_price / exchange_rate - coinbase_price
        premium_rate = premium / coinbase_price
        print('Premium: %.2f USD\nPremium Rate: %.1f %%' %
              (premium, premium_rate * 100))

        return premium_rate
    # Do some actual work here
    #Authenticate First Step

    from coinbase.wallet.client import Client

    client = Client('<YOUR API KEY>',
                    '<YOUR API KEY>',
                    api_version='2017-11-20')
    accounts = client.get_accounts()
    currency_code = 'GBP'  # can also use EUR, CAD, etc.

    for x in range(1):
        #Make the request
        #price = client.get_spot_price(currency=currency_code)
        #print ('Current bitcoin price in ' +  currency_code + " " +  price.amount)
        price = client.get_buy_price(currency_pair='BTC-GBP')
        #print ('Current BTC BUY price in ' +  currency_code + " " +  price.amount)
        price = client.get_sell_price(currency_pair='BTC-GBP')
        #print ('Current BTC SELL price in ' +  currency_code + " " +  price.amount)

    accounts = client.get_accounts()

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

#**********************TESTING************************
#**********************TESTING************************
#**********************TESTING************************
#**********************TESTING************************
Beispiel #14
0
                        level=logging.INFO)
except Exception as e:
    logging.basicConfig(filename='coinb.log',
                        format='%(asctime)s:%(levelname)s:%(message)s',
                        level=logging.INFO)
logging.info('container started')

# initialise coinbase client
c = Client('1', '2')

# mongo client
mongo_host = os.environ['mongosvc'].rstrip()
db_connection = MongoClient(mongo_host)
db = db_connection.cryptocurrency
collection = db.bitcoinprice

while True:
    spot_price = c.get_spot_price(currency_pair='BTC-EUR')
    buy_price = c.get_buy_price(currency_pair='BTC-EUR')
    sell_price = c.get_sell_price(currency_pair='BTC-EUR')
    #logging.debug('BTC price at %s: %s' %(time.time(),a['amount']))
    post = {
        'BTC-EUR spot price': int(float(spot_price['amount'])),
        'BTC-EUR buy price': int(float(buy_price['amount'])),
        'BTC-EUR sell price': int(float(sell_price['amount'])),
        'date': time.time()
    }
    collection.insert_one(post)
    logging.debug('loop complete')
    time.sleep(60)
Beispiel #15
0
 def test_get_buy_price(self):
     client = Client(api_key, api_secret)
     buy_price = client.get_buy_price()
     self.assertIsInstance(buy_price, APIObject)
     self.assertEqual(buy_price, mock_item)
Beispiel #16
0
from coinbase.wallet.client import Client
import sys
import os

SANDBOX_URL = 'https://api.sandbox.coinbase.com'
API_KEY = os.environ["CB_API"]
API_SECRET = os.environ["CB_SECRET"]
client = Client(API_KEY, API_SECRET, base_api_uri=SANDBOX_URL)

accounts = client.get_accounts()
price = client.get_buy_price(currency='USD')
price = float(price.amount)

#print accounts.data
while 1:
    for index, account in enumerate(accounts.data):
        if account['currency'] == 'USD':
            continue
        name = account['name']
        balance = account.balance.amount
        usd_value = float(balance) * price
        print "%i) %s: %s %s ($%.2f)" % (index + 1, name, balance,
                                         account.balance.currency,
                                         round(usd_value, 2))

    src = int(raw_input("\nFrom account: ")) - 1
    dest = int(raw_input("To account: ")) - 1
    if src == dest:
        sys.exit("Source and destination cannot be the same")

    amount = raw_input("Amount: ")
Beispiel #17
0
from coinbase.wallet.client import Client
import time
import os
from keys import API_KEY, API_SECRET, ACCOUNT_ID

client = Client(API_KEY, API_SECRET)

accounts = client.get_accounts()
assert isinstance(accounts.data, list)
assert accounts[0] is accounts.data[0]
assert len(accounts[::]) == len(accounts.data)

x = client.get_buy_price(currency_pair='BTC-CAD')
y = client.get_sell_price(currency_pair='BTC-CAD')
print(x["amount"])
s = time.strftime('%Y-%m-%d-%H-%M-%S')  #will produce 2011-10-24-13-10
print(s)

cwd = os.getcwd()
f = open(cwd + "\logs\\" + s + ".txt", "w+")

f.write(str(x['amount']) + '\n')
f.write(str(y['amount']) + '\n')
f.write(str(s) + '\n')

#print(client.get_spot_price(currency_pair = 'BTC-CAD'))

#print(client.get_time())
#print(client.get_primary_account())

#print(client.get_transactions(ACCOUNT_ID))
Beispiel #18
0
# https://developers.coinbase.com/docs/wallet/api-key-authentication
coinbase_api_key = ""
coinbase_api_secret = ""

# create coinbase client with your credentials
client = Client(coinbase_api_key, coinbase_api_secret)

# fetch default account ID from your coinbase account
print(term.format("Fetch Account Info\n", term.Attr.BOLD))
accounts_response = client.get_accounts()
print(term.format(accounts_response, term.Color.BLUE))
account_id = json.loads(accounts_response)["data"][0]["id"]

# check real time bitcoin price (total USD to buy one bitcoin)
print(term.format("Check Bitcoin Price\n", term.Attr.BOLD))
bitcoin_price_response = client.get_buy_price(currency_pair='BTC-USD')
print(term.format(bitcoin_price_response, term.Color.BLUE))
bitcoin_price = float(json.loads(bitcoin_price_response)["data"]["amount"])

# convert USD amount to bitcoin
bitcoin_amount = str(usd_amount / bitcoin_price)

# fetch default payment method ID from your coinbase account
print(term.format("Fetch Payment Method\n", term.Attr.BOLD))
payment_methods_response = client.get_payment_methods()
print(term.format(payment_methods_response, term.Color.BLUE))
payment_method_id = json.loads(payment_methods_response)["data"][0]["id"]

# buy bitcoin and commit order immediately
print(term.format("Purchase Bitcoin\n", term.Attr.BOLD))
buy_response = client.buy(account_id,
Beispiel #19
0
import requests
import json

api_key = "8wlkBw4r7dcm6ywC"
api_secret = "txDhu3ufzgOja1KfVyvjCWpIpxuYTkjk"

api_pro_trade "UagiFY36k+W7TYXXgNTlDIZQuVBAebznqrUZanSeJ9P4ZOe1xqPzrMLm4OOVtbuhql0feMzXJHvmZTEvrJU29Q=="

from coinbase.wallet.client import Client
client = Client(api_key, api_secret)
user = client.get_current_user()

print(json.dumps(user, indent=4, sort_keys=True))
print(client.get_buy_price(currency_pair = 'BTC-EUR'))
Beispiel #20
0
#Ratio threshold
thresh = 7299

#for buy triggers
pricelow1 = 2240
pricelow2 = 2375


#for sell triggers
mySellPrice = 8000

#Gets my account balance
#balance = account.balance

#Gets the current buy price for Bitcoin
buyPrice = client.get_buy_price().amount

#Gets the current sell price for Bitcoin
sellPrice = client.get_sell_price().amount
#Sell Price for Litecoin
sellPriceL = client.get_sell_price(currency_pair='LTC-USD').amount

#Gets the current price for Bitcoin
spotPrice = client.get_spot_price().amount

#Gets primary account which is Bitcoin wallet
#wallet = client.get_primary_account()

#Tests that can be deleted whenever
#print("Current buy price", buyPrice)
#print("Current sell price", sellPrice)
Beispiel #21
0
- 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()))
Beispiel #22
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
Beispiel #23
0
def get_ltc_buyprice():
    client = Client('apibuy', 'secretbuy')
    buy_ltc = client.get_buy_price(currency_pair = 'LTC-USD')
    return buy_ltc
Beispiel #24
0
import logging
import json
import requests
from coinbase.wallet.client import Client

#------------------------------------------------------------------
#All this code does is collect for the crypto prices

big_result_list = []

# Get API Key and API Secret from your coinbase account. Check out README for more info
# Also you can leave the API version as it is.
client = Client('API Key', 'API Secret', api_version='YYYY-MM-DD')

BTCUSD_price = client.get_buy_price(currency_pair='BTC-USD')
ETHUSD_price = client.get_buy_price(currency_pair='ETH-USD')
BTCUSD = (BTCUSD_price.get("amount"))
ETHUSD = (ETHUSD_price.get("amount"))

big_result_list.append("1 BTC = US$" + str(BTCUSD))
big_result_list.append("1 ETH = US$" + str(ETHUSD))


def coinGecko_data():
    mainsite = 'https://api.coingecko.com/api/v3/coins/bountie?tickers=false&market_data=true'
    request = requests.get(mainsite)
    jsonTest = request.json()

    return (jsonTest)
Beispiel #25
0
# accounts.refresh()

# print accounts

exchange_rates = client.get_exchange_rates()

data = pd.DataFrame(
    columns=['time', 'currency_pair', 'spot_price', 'buy_price', 'sell_price'])

log_num = 1
while True:
    for entry in range(14400):
        for currency in currencies:
            currency_pair = currency + '-USD'
            server_time = client.get_time()
            buy_price = client.get_buy_price(currency_pair=currency_pair)
            sell_price = client.get_sell_price(currency_pair=currency_pair)
            spot_price = client.get_spot_price(currency_pair=currency_pair)

            data = data.append(
                {
                    'time': server_time['iso'],
                    'currency_pair': currency_pair,
                    'spot_price': spot_price['amount'],
                    'buy_price': buy_price['amount'],
                    'sell_price': sell_price['amount']
                },
                ignore_index=True)

        with open('logs/log_{}.csv'.format(log_num), 'a') as f:
            if entry == 0:
Beispiel #26
0
import time
from playsound import playsound
import sys

API_key = "your_api_here"
API_secret = "your_api_secret_here"
coin = "coin_code_here"

client = Client(API_key, API_secret)
value = float(sys.argv[2])
state = sys.argv[1]
if(len(sys.argv)>3):
    value2 = float(sys.argv[3])

while True:
    currencies = client.get_buy_price(currency_pair = coin);
    print(currencies['amount'])
    if(state == 'abaixo'):
        if(float(currencies['amount']) <= value):
            playsound('alert.mp3')
            print('Ta abaixo');
    elif(state == 'acima'):
        if(float(currencies['amount']) >= value):
            playsound('alert.mp3')
            print('Ta acima');
    else:
        if(float(currencies['amount']) >= value):
            playsound('alert.mp3')
            print('Ta acima');
        if(float(currencies['amount']) <= value2):
            playsound('alert.mp3')
Beispiel #27
0
    :rtype: int, int, int
    """
    maximum = 0
    buy_day = 0
    sell_day = 0
    for i in range(len(prices) - 1):
        sell_price = max(prices[i + 1:])
        buy_price = min(prices[:i + 1])
        profit = sell_price - buy_price
        transaction_cost = buy_price * .03 + sell_price * .03

        if profit > transaction_cost:
            maximum = max(maximum, profit)

    return maximum, buy_day, sell_day


client = Client(api_key='', api_secret='')

historic_prices = client.get_historic_prices()
price_list = [float(day['price']) for day in historic_prices['prices']]
print(price_list)
max_profit = maxProfit(price_list)
print("Max profit:  $" + str(max_profit))

for i in range(10):
    time.sleep(10)
    print("Buy price " + str(client.get_buy_price(currency_pair='BTC-USD')))
    print("Sell price " + str(client.get_sell_price(currency_pair='BTC-USD')))
    print("Spot price " + str(client.get_spot_price(currency_pair='BTC-USD')))
Beispiel #28
0
 def test_get_buy_price(self):
   client = Client(api_key, api_secret)
   buy_price = client.get_buy_price()
   self.assertIsInstance(buy_price, APIObject)
   self.assertEqual(buy_price, mock_item)
Beispiel #29
0
    r = requests.get(api_url)

    #print(r.__dict__.keys())
    #print(json.load(r.content))
    json_data = json.loads(str(r.content, encoding='utf-8'))
    buy_price_B = json_data['data']['buy_price']
    sell_price_B = json_data['data']['sell_price']
    buy_BTCUSD_KRW = float(buy_price_B) / float(USDKRW)
    sell_BTCUSD_KRW = float(sell_price_B) / float(USDKRW)

    #coinbase data extraction
    api_key_C = 'place you api key for coinbase'
    api_secret_C = 'place your	api secret for coinbase'

    client = Client(api_key_C, api_secret_C)
    buy_BTCUSD = float(client.get_buy_price(currency_pair='BTC-USD'))
    sell_BTCUSD = float(client.get_sell_price(currency_pair='BTC-USD'))

    buy_price = float(buy_price['amount'])
    sell_price = float(sell_price['amount'])
    date_time_C = client.get_time()
    date_time_C = date_time_C["iso"]

    abs_diff = abs(buy_BTCUSD_KRW, buy_BTCUSD)
    abs_dif_per = abs_diff / max(buy_BTCUSD_KRW, buy_BTCUSD)

    data = [
        date_time_C, USDKRW, buy_BTCUSD_KRW, sell_BTCUSD_KRW, buy_BTCUSD,
        sell_BTCUSD, abs_diff, abs_dif_per
    ]
Beispiel #30
0
class CoinbaseBot:
    def __init__(self, api_key, api_secret):
        """
        Initializes an instance of the CoinbaseBot class. Initializes and sets the Coinbase API client.

        Args:
            api_key:str: API key for authenticating with the Coinbase API.
            api_secret:str: API secret for authenticating with the Coinbase API.
            client:coinbase.wallet.client.Client: Client object for authenticating using the provided api_key and api_secret. 
        """

        self.api_key = api_key
        self.api_secret = api_secret

        self.client = Client(self.api_key, self.api_secret)

    def live_prices(self, buy_currency_pair=None, sell_currency_pair=None):
        """
        Fetches the current buy price and sell price for specified cryto currency pairs. Can be same currency pair, or individual.

        Args:
            buy_currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation.
            sell_currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation.
        
        Returns:
            dict: Most recent buy and sell data for the specified currency pair. 
                  Includes the "amount" or price, and two individual fields denoting the pair.
        """

        combined_data = {}

        buy_data = self.live_buy_price(buy_currency_pair)
        sell_data = self.live_sell_price(sell_currency_pair)

        combined_data['buy'] = buy_data
        combined_data['sell'] = sell_data

        return combined_data

    def live_buy_price(self, currency_pair):
        """
        Fetches the current buy price for a given cryto currency pair.

        Args:
            currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation.

        Returns:
            dict: Key value dictionary object.
        """

        return self.client.get_buy_price(currency_pair=currency_pair)

    def live_sell_price(self, currency_pair):
        """
        Fetches the current sell price for a given cryto currency pair.

        Args:
            currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation.
        
        Returns:
            dict: Key value dictionary object.
        """

        return self.client.get_sell_price(currency_pair=currency_pair)
Beispiel #31
0
from config import coinbase_api_key, coinbase_api_secret

SANDBOX_URL = 'https://api.sandbox.coinbase.com'

client = Client(
    coinbase_api_key(),
    coinbase_api_secret(),
    base_api_uri=SANDBOX_URL)

payment_methods = client.get_payment_methods()

account = client.get_primary_account()
payment_method = client.get_payment_methods()[0]

buy_price_threshold = 200
sell_price_threshold = 500

buy_price = client.get_buy_price(currency='USD')
sell_price = client.get_sell_price(currency='USD')

if float(sell_price.amount) <= sell_price_threshold:
  sell = account.sell(amount='1',
                      currency="BTC",
                      payment_method=payment_method.id)

if float(buy_price.amount) <= buy_price_threshold:
  buy = account.buy(amount='1',
                    currency="BTC",
                    payment_method=payment_method.id)
Beispiel #32
0
client = Client(api_key="API_KEY",
                api_secret="API_SECRET",
                api_version="YYYY-MM-DD")

# Making sure a verified payment method is associated with the Coinbase account.
#payment_methods = client.get_payment_methods()

# Buy and Sell bitcoins

# account = client.get_primary_account()
# payment_method = client.get_payment_methods()[0]

buy_price_threshold = 200
sell_price_threshold = 500

buy_price = client.get_buy_price(currency='EUR')
sell_price = client.get_sell_price(currency='EUR')

if float(sell_price.amount) <= sell_price_threshold:
    sell = account.sell(amount='1',
                        currency="BTC",
                        payment_method=payment_method.id)

if float(buy_price.amount) <= buy_price_threshold:
    buy = account.buy(amount='1',
                      currency="BTC",
                      payment_method=payment_method.id)

#while 1: # Infinite loop
for y in range(1):
Beispiel #33
0

client = Client(api_key="API_KEY", api_secret="API_SECRET", api_version="YYYY-MM-DD");

# Making sure a verified payment method is associated with the Coinbase account.
#payment_methods = client.get_payment_methods()

# Buy and Sell bitcoins

# account = client.get_primary_account()
# payment_method = client.get_payment_methods()[0]

buy_price_threshold  = 200
sell_price_threshold = 500

buy_price  = client.get_buy_price(currency='EUR')
sell_price = client.get_sell_price(currency='EUR')


if float(sell_price.amount) <= sell_price_threshold:
  sell = account.sell(amount='1',
                      currency="BTC",
                      payment_method=payment_method.id)


if float(buy_price.amount) <= buy_price_threshold:
  buy = account.buy(amount='1',
                    currency="BTC",
                    payment_method=payment_method.id)

#while 1: # Infinite loop