Exemplo n.º 1
0
class coinbase_api():
    def __init__(self):
        self.coinbase_key_id = os.environ['COINBASE_KEY_ID']
        self.coinbase_secret_key = os.environ['COINBASE_SECRET_KEY']
        self.coinbase_api_version = os.environ['COINBASE_API_VERSION']
        self.coinbase_conn = None

    def connect(self):
        """
        Set object attribute coinbase_conn with a live Coinbase API connection object.
        :return: None
        """
        self.coinbase_conn = Client(self.coinbase_key_id,
                                    self.coinbase_secret_key,
                                    api_version=self.coinbase_api_version)

    def get_historic_prices(self, currency, period):
        """
        Get BTC prices
        :param currency: The international currency that the BTC price will be cited in (e.g. 'USD').
        :param period: The historical time period to get BTC prices from.
        :return: JSON dump (if connection is live) or None (if no connection).
        """
        if self.coinbase_conn is not None:
            return self.coinbase_conn.get_historic_prices(currency=currency,
                                                          period=period)
Exemplo n.º 2
0
# This is where you can test the algo on historic data from CB. Tests will be done on daily closing data of BTCUSD
from coinbase.wallet.client import Client
import matplotlib.pyplot as plt
from api_info import cb_api_secret, cb_api_key

client = Client(cb_api_key, cb_api_secret)
currency_pair = "BTC-USD"
period = "all"
# Entry and exit periods for trades.
entry_period = 1
exit_period = 1

# Creating a list of historical data into two lists. One with prices, one with times.
hist_data = client.get_historic_prices(currency_pair=currency_pair,
                                       period=period).get("prices")
hist_prices = []
hist_dates = []
for i in hist_data:
    hist_prices.append(float(i["price"]))
    hist_dates.append((i["time"]))
# print("Hist.prices: ", len(hist_prices), hist_prices)

# Looping through the price list and searching for values which are higher/lower than entry_period
# to specify BREAKOUT point to enter LONG/SHORT position
long_price = []
long_id = []
long_date = []
breakout_long = []
short_price = []
short_id = []
short_date = []
Exemplo n.º 3
0
'''

from coinbase.wallet.client import Client
from coinbase.wallet.model import APIObject

api_key = 'R6NS3FRYnJXKJmI7'
api_secret = '2b4Pdpji2iYZrdBMalPEKerWKs8FCFh6'

#Fazer autenticação
client = Client(api_key, api_secret)

#Pegar preço de mercado - Argumento date opcional
#pode ser utilizada para pegar o preço em um dia específico
#o argumento é no formato date = 'YYYY-MM-DD'
price = client.get_spot_price(currency_pair='BTC-USD',
                              date='2018-01-01T07:10:40')
print(price)

#Pegar o histórico de preços - Esta função pega o histórico de preços.
#O único parâmetro dela é  o period que pode ter os seguintes valores:
#hour - Pega o histórico da última hora (361 pontos)
#day - Pega o histórico das últimas 24h (360 pontos)
#week - Pega o histórico da última semana (316 pontos)
#month - Pega o histórico do último mês (360 pontos)
#year - Pega o histórico do último ano (365 pontos)
#all - Pegar o histórico do último ano(não entendi, mas pega mais pontos)
historic = client.get_historic_prices(currency_pair='BTC-USD', period='hour')

print(historic)
print(len(historic["prices"]))
Exemplo n.º 4
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')))
Exemplo n.º 5
0
 def test_get_historic_prices(self):
     client = Client(api_key, api_secret)
     historic_prices = client.get_historic_prices(currency_pair='BTC-USD')
     self.assertIsInstance(historic_prices, APIObject)
     self.assertEqual(historic_prices, mock_item)
Exemplo n.º 6
0
class Client:
    def __init__(self):
        self.coinbase_client = CoinbaseClient(
            'kjbqArvnGOKiVsCL', '1EtHiISTUavVa5CxqUpKIxi2bmEddW2N')
        self.currency_code = 'USD'  # can also use EUR, CAD, etc.
        self.sp_api_client = SpreadsheetsApi()
        self.auth_api_client = AuthenticationApi()
        self._set_token()
        self.wb = '067474f68bcc4fada0da5b85fe9b6b62'
        self.tb = 'a47eddaf73b64709a2db2d893e3dfddd'

    def _set_token(self):
        Configuration().access_token = self.auth_api_client.oauth2_token_post(
            client_id='04fffc2536fa4978808ac680dbbecacc',
            x_api_key='',
            client_secret='4e8ecf9b8d20504352b7539dc0a664095ed52a80ff8517a0',
            grant_type='client_credentials').access_token
        # Renew token every minute
        t = threading.Timer(60.0, self._set_token)
        t.daemon = True
        t.start()

    def set_price_in_sheet(self):
        # Make the request
        btc_price = self.coinbase_client.get_spot_price(
            currency_pair='BTC-USD')
        self.coinbase_client.get_historic_prices()
        resp = requests.get(
            url='https://api.coinbase.com/v2/prices/ETH-USD/spot',
            headers={
                'Authorization': 'Bearer ' + Configuration().access_token
            })
        eth = json.loads(resp.text)
        eth_price = eth['data']['amount']

        # Update the Spreadsheet
        resp = self.sp_api_client.spreadsheets_spreadsheet_id_sheets_sheet_id_data_put(
            '067474f68bcc4fada0da5b85fe9b6b62',
            'a47eddaf73b64709a2db2d893e3dfddd',
            {
                "values": [["Bitcoin price (in dollars)", btc_price.amount],
                           ["ETH price (in dollars)", eth_price]]
            },
            'fakekey',
            region='A1:B2',
        )

    def set_exchange_rates_in_sheet(self):
        while True:
            raw_input("Press 'Enter' to refresh exchange rates")
            rates = self.coinbase_client.get_exchange_rates(currency="BTC")
            values = [["BTC Exchange Rates", ""]]
            for k, v in rates["rates"].iteritems():
                values.append([k, v])
            # Update the Spreadsheet
            resp = self.sp_api_client.spreadsheets_spreadsheet_id_sheets_sheet_id_data_put(
                '067474f68bcc4fada0da5b85fe9b6b62',
                'a47eddaf73b64709a2db2d893e3dfddd',
                {"values": values},
                'fakekey',
                region='A4:B',
            )
Exemplo n.º 7
0
 def test_get_historic_prices(self):
     client = Client(api_key, api_secret)
     historic_prices = client.get_historic_prices(currency_pair='BTC-USD')
     self.assertIsInstance(historic_prices, APIObject)
     self.assertEqual(historic_prices, mock_item)