def test_getOrdersInvalidStatus():
    filename = 'config.json'

    with open(filename) as config_file:
        config = json.load(config_file)

        api_key = ''
        api_secret = ''
        api_passphrase = ''
        api_url = ''
        if 'api_key' in config and 'api_secret' in config and 'api_pass' in config and 'api_url' in config:
            api_key = config['api_key']
            api_secret = config['api_secret']
            api_passphrase = config['api_pass']
            api_url = config['api_url']

        elif 'api_key' in config['coinbasepro'] and 'api_secret' in config[
                'coinbasepro'] and 'api_passphrase' in config[
                    'coinbasepro'] and 'api_url' in config['coinbasepro']:
            api_key = config['coinbasepro']['api_key']
            api_secret = config['coinbasepro']['api_secret']
            api_passphrase = config['coinbasepro']['api_passphrase']
            api_url = config['coinbasepro']['api_url']

    exchange = AuthAPI(api_key, api_secret, api_passphrase, api_url)
    assert type(exchange) is AuthAPI

    with pytest.raises(ValueError) as execinfo:
        exchange.getOrders(status='ERROR')
    assert str(execinfo.value) == 'Invalid order status.'
예제 #2
0
    def getOrders(self, market='', action='', status='all'):
        """Retrieves orders either live or simulation

        Parameters
        ----------
        market : str, optional
            Filters orders by market
        action : str, optional
            Filters orders by action
        status : str
            Filters orders by status, defaults to 'all'
        """

        if market != '':
            # validate market is syntactically correct
            p = re.compile(r"^[A-Z]{3,4}\-[A-Z]{3,4}$")
            if not p.match(market):
                raise TypeError('Coinbase Pro market is invalid.')

        if action != '':
            # validate action is either a buy or sell
            if not action in ['buy', 'sell']:
                raise ValueError('Invalid order action.')

        # validate status is open, pending, done, active or all
        if not status in ['open', 'pending', 'done', 'active', 'all']:
            raise ValueError('Invalid order status.')

        if self.mode == 'live':
            # if config is provided and live connect to Coinbase Pro account portfolio
            model = AuthAPI(self.api_key, self.api_secret, self.api_pass,
                            self.api_url)
            # retrieve orders from live Coinbase Pro account portfolio
            self.orders = model.getOrders(market, action, status)
            return self.orders
        else:
            # return dummy orders
            if market == '':
                return self.orders
            else:
                return self.orders[self.orders['market'] == market]
def test_getOrdersValidStatusActive():
    filename = 'config.json'

    with open(filename) as config_file:
        config = json.load(config_file)

        api_key = ''
        api_secret = ''
        api_passphrase = ''
        api_url = ''
        if 'api_key' in config and 'api_secret' in config and 'api_pass' in config and 'api_url' in config:
            api_key = config['api_key']
            api_secret = config['api_secret']
            api_passphrase = config['api_pass']
            api_url = config['api_url']

        elif 'api_key' in config['coinbasepro'] and 'api_secret' in config[
                'coinbasepro'] and 'api_passphrase' in config[
                    'coinbasepro'] and 'api_url' in config['coinbasepro']:
            api_key = config['coinbasepro']['api_key']
            api_secret = config['coinbasepro']['api_secret']
            api_passphrase = config['coinbasepro']['api_passphrase']
            api_url = config['coinbasepro']['api_url']

    exchange = AuthAPI(api_key, api_secret, api_passphrase, api_url)
    assert type(exchange) is AuthAPI

    df = exchange.getOrders(status='active')

    if len(df) == 0:
        pass
    else:
        actual = df.columns.to_list()
        expected = [
            'created_at', 'market', 'action', 'type', 'size', 'value',
            'status', 'price'
        ]
        assert len(actual) == len(expected)
        assert all([a == b for a, b in zip(actual, expected)])
def getValidOrderMarket() -> str:
    filename = 'config.json'
    assert os.path.exists(filename) == True
    with open(filename) as config_file:
        config = json.load(config_file)

        if 'api_key' in config and 'api_secret' in config and (
                'api_pass' in config
                or 'api_passphrase' in config) and 'api_url' in config:
            api_key = config['api_key']
            api_secret = config['api_secret']
            if 'api_pass' in config:
                api_passphrase = config['api_pass']
            else:
                api_passphrase = config['api_passphrase']
            api_url = config['api_url']
        elif 'coinbasepro' in config:
            if 'api_key' in config['coinbasepro'] and 'api_secret' in config[
                    'coinbasepro'] and 'api_passphrase' in config[
                        'coinbasepro'] and 'api_url' in config['coinbasepro']:
                api_key = config['coinbasepro']['api_key']
                api_secret = config['coinbasepro']['api_secret']
                api_passphrase = config['coinbasepro']['api_passphrase']
                api_url = config['coinbasepro']['api_url']
            else:
                return DEFAULT_ORDER_MARKET
        else:
            return DEFAULT_ORDER_MARKET

        time.sleep(0.5)
        exchange = AuthAPI(api_key, api_secret, api_passphrase, api_url)
        df = exchange.getOrders()
        if len(df) == 0:
            return DEFAULT_ORDER_MARKET

        return df['market'].tail(1).values[0]
    return DEFAULT_ORDER_MARKET
예제 #5
0
    def getOrders(self, market='', action='', status='all'):
        """Retrieves orders either live or simulation

        Parameters
        ----------
        market : str, optional
            Filters orders by market
        action : str, optional
            Filters orders by action
        status : str
            Filters orders by status, defaults to 'all'
        """

        # validate market is syntactically correct
        self._checkMarketSyntax(market)

        if action != '':
            # validate action is either a buy or sell
            if not action in ['buy', 'sell']:
                raise ValueError('Invalid order action.')

        # validate status is open, pending, done, active or all
        if not status in [
                'open', 'pending', 'done', 'active', 'all', 'filled'
        ]:
            raise ValueError('Invalid order status.')

        if self.app.getExchange() == 'binance':
            if self.mode == 'live':
                resp = self.client.get_all_orders(symbol=market)
                if len(resp) > 0:
                    df = pd.DataFrame(resp)
                else:
                    df = pd.DataFrame()

                if len(df) == 0:
                    return pd.DataFrame()

                df = df[[
                    'time', 'symbol', 'side', 'type', 'executedQty',
                    'cummulativeQuoteQty', 'status'
                ]]
                df.columns = [
                    'created_at', 'market', 'action', 'type', 'size', 'value',
                    'status'
                ]
                df['created_at'] = df['created_at'].apply(
                    lambda x: int(str(x)[:10]))
                df['created_at'] = df['created_at'].astype("datetime64[s]")
                df['size'] = df['size'].astype(float)
                df['value'] = df['value'].astype(float)
                df['action'] = df['action'].str.lower()
                df['type'] = df['type'].str.lower()
                df['status'] = df['status'].str.lower()
                df['price'] = df['value'] / df['size']

                # pylint: disable=unused-variable
                for k, v in df.items():
                    if k == 'status':
                        df[k] = df[k].map(self.__convertStatus)

                if action != '':
                    df = df[df['action'] == action]
                    df = df.reset_index(drop=True)

                if status != 'all' and status != '':
                    df = df[df['status'] == status]
                    df = df.reset_index(drop=True)

                return df
            else:
                # return dummy orders
                if market == '':
                    return self.orders
                else:
                    if (len(self.orders) > 0):
                        return self.orders[self.orders['market'] == market]
                    else:
                        return pd.DataFrame()
        if self.app.getExchange() == 'coinbasepro':
            if self.mode == 'live':
                # if config is provided and live connect to Coinbase Pro account portfolio
                model = CBAuthAPI(self.app.getAPIKey(),
                                  self.app.getAPISecret(),
                                  self.app.getAPIPassphrase(),
                                  self.app.getAPIURL())
                # retrieve orders from live Coinbase Pro account portfolio
                self.orders = model.getOrders(market, action, status)
                return self.orders
            else:
                # return dummy orders
                if market == '':
                    return self.orders
                else:
                    return self.orders[self.orders['market'] == market]
예제 #6
0
from models.CoinbasePro import AuthAPI

with open('config.json') as config_file:
    config = json.load(config_file)

model = AuthAPI(config['api_key'], config['api_secret'], config['api_pass'], config['api_url'])
resp = model.authAPI('GET','orders?status=all')
print (resp)

accounts = model.getAccounts()
print (accounts)

#account = model.getAccount('00000000-0000-0000-0000-000000000000')
#print (account)

orders1 = model.getOrders()
print (orders1)

orders2 = model.getOrders('BTC-GBP')
print (orders2)

orders3 = model.getOrders('BTC-GBP', 'buy')
print (orders3)

orders4 = model.getOrders('BTC-GBP', 'buy', 'done')
print (orders4)

#order = model.marketBuy('BTC-GBP', 100)
#print (order)

#order = model.marketSell('BTC-GBP', 0.001)
예제 #7
0
    def saveTrackerCSV(self, market='', save_file='tracker.csv'):
        """Saves order tracker to CSV

        Parameters
        ----------
        market : str, optional
            Filters orders by market
        save_file : str
            Output CSV file
        """

        if market != '':
            # validate market is syntactically correct
            p = re.compile(r"^[A-Z]{3,4}\-[A-Z]{3,4}$")
            if not p.match(market):
                raise TypeError('Coinbase Pro market is invalid.')

        if self.mode == 'live':
            # if config is provided and live connect to Coinbase Pro account portfolio
            model = AuthAPI(self.api_key, self.api_secret, self.api_pass,
                            self.api_url)
            # retrieve orders from live Coinbase Pro account portfolio
            df = model.getOrders(market, '', 'done')
        else:
            # return dummy orders
            if market == '':
                df = self.orders
            else:
                df = self.orders[self.orders['market'] == market]

        if list(df.keys()) != [
                'created_at', 'market', 'action', 'type', 'size', 'value',
                'status', 'price'
        ]:
            # no data, return early
            return False

        df_tracker = pd.DataFrame()

        last_action = ''
        for market in df['market'].sort_values().unique():
            df_market = df[df['market'] == market]

            df_buy = pd.DataFrame()
            df_sell = pd.DataFrame()

            pair = 0
            # pylint: disable=unused-variable
            for index, row in df_market.iterrows():
                if row['action'] == 'buy':
                    pair = 1

                if pair == 1 and (row['action'] != last_action):
                    if row['action'] == 'buy':
                        df_buy = row
                    elif row['action'] == 'sell':
                        df_sell = row

                if row['action'] == 'sell' and len(df_buy) != 0:
                    df_pair = pd.DataFrame([[
                        df_sell['status'], df_buy['market'],
                        df_buy['created_at'], df_buy['type'], df_buy['size'],
                        df_buy['value'], df_buy['price'],
                        df_sell['created_at'], df_sell['type'],
                        df_sell['size'], df_sell['value'], df_sell['price']
                    ]],
                                           columns=[
                                               'status', 'market', 'buy_at',
                                               'buy_type', 'buy_size',
                                               'buy_value', 'buy_price',
                                               'sell_at', 'sell_type',
                                               'sell_size', 'sell_value',
                                               'sell_price'
                                           ])
                    df_tracker = df_tracker.append(df_pair, ignore_index=True)
                    pair = 0

                last_action = row['action']

        if list(df_tracker.keys()) != [
                'status', 'market', 'buy_at', 'buy_type', 'buy_size',
                'buy_value', 'buy_price', 'sell_at', 'sell_type', 'sell_size',
                'sell_value', 'sell_price'
        ]:
            # no data, return early
            return False

        df_tracker['profit'] = np.subtract(df_tracker['sell_value'],
                                           df_tracker['buy_value'])
        df_tracker['margin'] = np.multiply(
            np.true_divide(df_tracker['profit'], df_tracker['sell_value']),
            100)
        df_sincebot = df_tracker[df_tracker['buy_at'] > '2021-02-1']

        try:
            df_sincebot.to_csv(save_file, index=False)
        except OSError:
            raise SystemExit('Unable to save: ', save_file)
예제 #8
0
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('ETH-')
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('LTC-')
          and account.getBalance(cryptoMarket) > 0.1):
        last_action = 'BUY'
    elif (market.startswith('XLM-') and account.getBalance(cryptoMarket) > 35):
        last_action = 'BUY'
    elif (account.getBalance(fiatMarket) > 30):
        last_action = 'SELL'

    authAPI = AuthAPI(config['api_key'], config['api_secret'],
                      config['api_pass'], config['api_url'])
    orders = authAPI.getOrders(market)
    if len(orders) > 0:
        df = orders[-1:]
        price = df[df.action == 'buy']['price']
        if len(price) > 0:
            last_buy = float(truncate(price, 2))


def executeJob(sc, market, granularity, tradingData=pd.DataFrame()):
    """Trading bot job which runs at a scheduled interval"""
    global action, buy_count, buy_sum, failsafe, iterations, last_action, last_buy, last_df_index, sell_count, sell_sum, x_since_buy, x_since_sell

    # increment iterations
    iterations = iterations + 1

    if is_sim == 0:
예제 #9
0
            if 'cryptoMarket' in config:
                base_currency = config['cryptoMarket']
            elif 'base_currency' in config:
                base_currency = config['base_currency']

            if 'fiatMarket' in config:
                quote_currency = config['fiatMarket']
            elif 'base_currency' in config:
                quote_currency = config['quote_currency']

            market = base_currency + '-' + quote_currency

            api = CBAuthAPI(api_key, api_secret, api_pass)

            orders = api.getOrders()
            df = pd.concat([df, orders])

            transfers = api.getTransfers()
            df = pd.concat([df, transfers])

    df['created_at'] = df['created_at'].map(
        lambda x: re.sub(r"\.\d{1,6}\+00$", "", str(x)))
    df['created_at'] = df['created_at'].map(
        lambda x: re.sub(r"\+00:00$", "", str(x)))

    save_file = 'profitandloss.csv'

    try:
        df.to_csv(save_file, index=False)
    except OSError:
예제 #10
0
                sys.exit()

            if 'cryptoMarket' in config:
                base_currency = config['cryptoMarket']
            elif 'base_currency' in config:
                base_currency = config['base_currency']

            if 'fiatMarket' in config:
                quote_currency = config['fiatMarket']
            elif 'base_currency' in config:
                quote_currency = config['quote_currency']

            market = base_currency + '-' + quote_currency

            api = CBAuthAPI(api_key, api_secret, api_pass)
            orders = api.getOrders(market)

            last_action = ''
            if len(orders) > 0:
                for market in orders['market'].sort_values().unique():
                    df_market = orders[orders['market'] == market]
            else:
                df_market = pd.DataFrame()

            df_buy = pd.DataFrame()
            df_sell = pd.DataFrame()

            pair = 0
            # pylint: disable=unused-variable
            for index, row in df_market.iterrows():
                if row['action'] == 'buy':
with open('config.json') as config_file:
    config = json.load(config_file)

model = AuthAPI(config['api_key'], config['api_secret'], config['api_pass'],
                config['api_url'])

#resp = model.authAPI('GET','orders?status=all')
#print (resp)

#accounts = model.getAccounts()
#print (accounts)

#account = model.getAccount('00000000-0000-0000-0000-000000000000')
#print (account)

orders1 = model.getOrders()
print(orders1)

#orders2 = model.getOrders('BTC-GBP')
#print (orders2)

#orders3 = model.getOrders('BTC-GBP', 'buy')
#print (orders3)

#orders4 = model.getOrders('BTC-GBP', 'buy', 'done')
#print (orders4)

#order = model.marketBuy('BTC-GBP', 100)
#print (order)

#order = model.marketSell('BTC-GBP', 0.001)
예제 #12
0
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('ETH-')
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('LTC-')
          and account.getBalance(cryptoMarket) > 0.1):
        last_action = 'BUY'
    elif (market.startswith('XLM-') and account.getBalance(cryptoMarket) > 35):
        last_action = 'BUY'
    elif (account.getBalance(fiatMarket) > 30):
        last_action = 'SELL'

    authAPI = AuthAPI(config['api_key'], config['api_secret'],
                      config['api_pass'], config['api_url'])
    orders = authAPI.getOrders(market, '', 'done')
    if len(orders) > 0:
        df = orders[-1:]
        price = df[df.action == 'buy']['price']
        if len(price) > 0:
            last_buy = float(truncate(price, 2))


def executeJob(sc, market, granularity, tradingData=pd.DataFrame()):
    """Trading bot job which runs at a scheduled interval"""
    global action, buy_count, buy_sum, failsafe, iterations, last_action, last_buy, last_df_index, sell_count, sell_sum, buy_state, x_since_buy, x_since_sell

    # increment iterations
    iterations = iterations + 1

    # coinbase pro public api