def __init__(self, app:PyCryptoBot, account:TradingAccount) -> None: if app.getExchange() == 'binance': self.api = BAuthAPI(app.getAPIKey(), app.getAPISecret(), app.getAPIURL()) elif app.getExchange() == 'coinbasepro': self.api = CAuthAPI(app.getAPIKey(), app.getAPISecret(), app.getAPIPassphrase(), app.getAPIURL()) else: self.api = None self.app = app self.account = account self.action = 'WAIT' self.buy_count = 0 self.buy_state = '' self.buy_sum = 0 self.eri_text = '' self.fib_high = 0 self.fib_low = 0 self.first_buy_size = 0 self.iterations = 0 self.last_action = 'WAIT' self.last_buy_size = 0 self.last_buy_price = 0 self.last_buy_filled = 0 self.last_buy_fee = 0 self.last_buy_high = 0 self.last_df_index = '' self.sell_count = 0 self.sell_sum = 0
def getTakerFee(self): if self.exchange == 'coinbasepro': api = CBAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIPassphrase(), self.getAPIURL()) return api.getTakerFee() elif self.exchange == 'binance': api = BAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIURL()) return api.getTakerFee(self.getMarket()) else: return 0.005
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': # if config is provided and live connect to Binance account portfolio model = BAuthAPI(self.app.getAPIKey(), self.app.getAPISecret(), self.app.getAPIURL()) # retrieve orders from live Binance 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] 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]
def __init__(self, app: PyCryptoBot, account: TradingAccount) -> None: if app.getExchange() == Exchange.BINANCE: self.api = BAuthAPI( app.getAPIKey(), app.getAPISecret(), app.getAPIURL(), recv_window=app.getRecvWindow(), ) elif app.getExchange() == Exchange.COINBASEPRO: self.api = CAuthAPI( app.getAPIKey(), app.getAPISecret(), app.getAPIPassphrase(), app.getAPIURL(), ) elif app.getExchange() == Exchange.KUCOIN: self.api = KAuthAPI( app.getAPIKey(), app.getAPISecret(), app.getAPIPassphrase(), app.getAPIURL(), ) else: self.api = None self.app = app self.account = account self.action = "WAIT" self.buy_count = 0 self.buy_state = "" self.buy_sum = 0 self.eri_text = "" self.fib_high = 0 self.fib_low = 0 self.first_buy_size = 0 self.iterations = 0 self.last_action = "WAIT" self.last_buy_size = 0 self.last_buy_price = 0 self.last_buy_filled = 0 self.last_buy_fee = 0 self.last_buy_high = 0 self.last_sell_size = 0 self.last_df_index = "" self.sell_count = 0 self.sell_sum = 0 self.margintracker = 0 self.profitlosstracker = 0 self.feetracker = 0 self.buy_tracker = 0 self.last_api_call_datetime = datetime.datetime.now( ) - datetime.timedelta(minutes=2) self.exchange_last_buy = None
def marketSell(self, market, base_currency, sell_percent=100): if self.is_live == 1: if isinstance(sell_percent, int): if sell_percent > 0 and sell_percent < 100: base_currency = (sell_percent / 100) * base_currency if self.exchange == 'coinbasepro': api = CBAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIPassphrase(), self.getAPIURL()) return api.marketSell(market, base_currency) elif self.exchange == 'binance': api = BAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIURL()) return api.marketSell(market, base_currency) else: return None
def marketBuy(self, market, quote_currency, buy_percent=100): if self.is_live == 1: if isinstance(buy_percent, int): if buy_percent > 0 and buy_percent < 100: quote_currency = (buy_percent / 100) * quote_currency if self.exchange == 'coinbasepro': api = CBAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIPassphrase(), self.getAPIURL()) return api.marketBuy(market, self.truncate(quote_currency, 2)) elif self.exchange == 'binance': api = BAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIURL()) return api.marketBuy(market, quote_currency) else: return None
def getTakerFee(self): if self.isSimulation() is True and self.exchange == 'coinbasepro': return 0.005 # default lowest fee tier elif self.isSimulation() is True and self.exchange == 'binance': return 0.001 # default lowest fee tier elif self.exchange == 'coinbasepro': api = CBAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIPassphrase(), self.getAPIURL()) return api.getTakerFee() elif self.exchange == 'binance': api = BAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIURL()) return api.getTakerFee() else: return 0.005
def getBalance(self, currency=''): """Retrieves balance either live or simulation Parameters ---------- currency: str, optional Filters orders by currency """ if self.app.getExchange() == 'binance': if self.mode == 'live': model = BAuthAPI(self.app.getAPIKey(), self.app.getAPISecret()) df = model.getAccount() if isinstance(df, pd.DataFrame): if currency == '': # retrieve all balances return df else: # retrieve balance of specified currency df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) else: return 0.0 else: # return dummy balances if currency == '': # retrieve all balances return self.balance else: if self.app.getExchange() == 'binance': self.balance = self.balance.replace('QUOTE', currency) else: # replace QUOTE and BASE placeholders if currency in ['EUR', 'GBP', 'USD']: self.balance = self.balance.replace( 'QUOTE', currency) else: self.balance = self.balance.replace( 'BASE', currency) if self.balance.currency[self.balance.currency.isin( [currency])].empty: self.balance.loc[len( self.balance)] = [currency, 0, 0, 0] # retrieve balance of specified currency df = self.balance df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) else: 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()) if currency == '': # retrieve all balances return model.getAccounts()[[ 'currency', 'balance', 'hold', 'available' ]] else: df = model.getAccounts() # retrieve balance of specified currency df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) else: # return dummy balances if currency == '': # retrieve all balances return self.balance else: # replace QUOTE and BASE placeholders if currency in ['EUR', 'GBP', 'USD']: self.balance = self.balance.replace('QUOTE', currency) elif currency in ['BCH', 'BTC', 'ETH', 'LTC', 'XLM']: self.balance = self.balance.replace('BASE', currency) if self.balance.currency[self.balance.currency.isin( [currency])].empty == True: self.balance.loc[len( self.balance)] = [currency, 0, 0, 0] # retrieve balance of specified currency df = self.balance df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( self.app.truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4))
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() == Exchange.BINANCE: if self.mode == "live": # if config is provided and live connect to Binance account portfolio model = BAuthAPI( self.app.getAPIKey(), self.app.getAPISecret(), self.app.getAPIURL(), recv_window=self.app.getRecvWindow(), ) # retrieve orders from live Binance 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] if self.app.getExchange() == Exchange.KUCOIN: if self.mode == 'live': # if config is provided and live connect to Kucoin account portfolio model = KAuthAPI( self.app.getAPIKey(), self.app.getAPISecret(), self.app.getAPIPassphrase(), self.app.getAPIURL(), use_cache=self.app.useKucoinCache(), ) # retrieve orders from live Kucoin account portfolio self.orders = model.getOrders(market, action, status) return self.orders else: if market == '': return self.orders else: return self.orders[self.orders['market'] == market] if self.app.getExchange() == Exchange.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: if "market" in self.orders: return self.orders[self.orders["market"] == market] else: return pd.DataFrame() if self.app.getExchange() == Exchange.DUMMY: return self.orders[[ "created_at", "market", "action", "type", "size", "filled", "fees", "price", "status", ]]
def getBalance(self, currency=""): """Retrieves balance either live or simulation Parameters ---------- currency: str, optional Filters orders by currency """ if self.app.getExchange() == Exchange.KUCOIN: if self.mode == 'live': model = KAuthAPI( self.app.getAPIKey(), self.app.getAPISecret(), self.app.getAPIPassphrase(), self.app.getAPIURL(), use_cache=self.app.useKucoinCache(), ) trycnt, maxretry = (0, 5) while trycnt <= maxretry: df = model.getAccounts() if isinstance(df, pd.DataFrame) and len(df) > 0: if currency == '': # retrieve all balances return df else: # retrieve balance of specified currency df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( truncate( float( df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float( df[df['currency'] == currency] ['available'].values[0]), 4)) else: time.sleep(5) trycnt += 1 else: return 0.0 else: # return dummy balances if currency == '': # retrieve all balances return self.balance else: self.balance = self.balance.replace('QUOTE', currency) if self.balance.currency[self.balance.currency.isin( [currency])].empty: self.balance.loc[len( self.balance)] = [currency, 0, 0, 0] # retrieve balance of specified currency df = self.balance df_filtered = df[df['currency'] == currency]['available'] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ['EUR', 'GBP', 'USD']: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) elif self.app.getExchange() == Exchange.BINANCE: if self.mode == "live": model = BAuthAPI( self.app.getAPIKey(), self.app.getAPISecret(), self.app.getAPIURL(), recv_window=self.app.getRecvWindow(), ) df = model.getAccount() if isinstance(df, pd.DataFrame): if currency == "": # retrieve all balances return df else: # return nil if dataframe is empty if len(df) == 0: return 0.0 # retrieve balance of specified currency df_filtered = df[df["currency"] == currency]["available"] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ["EUR", "GBP", "USD"]: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) else: return 0.0 else: # return dummy balances if currency == "": # retrieve all balances return self.balance else: if self.app.getExchange() == Exchange.BINANCE: self.balance = self.balance.replace("QUOTE", currency) else: # replace QUOTE and BASE placeholders if currency in ["EUR", "GBP", "USD"]: self.balance = self.balance.replace( "QUOTE", currency) else: self.balance = self.balance.replace( "BASE", currency) if self.balance.currency[self.balance.currency.isin( [currency])].empty: self.balance.loc[len( self.balance)] = [currency, 0, 0, 0] # retrieve balance of specified currency df = self.balance df_filtered = df[df["currency"] == currency]["available"] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ["EUR", "GBP", "USD"]: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) elif self.app.getExchange() == Exchange.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(), ) trycnt, maxretry = (0, 5) while trycnt <= maxretry: df = model.getAccounts() if len(df) > 0: # retrieve all balances, but check the resp if currency == "" and "balance" not in df: time.sleep(5) trycnt += 1 # retrieve all balances and return elif currency == "": return df else: # retrieve balance of specified currency df_filtered = df[df["currency"] == currency]["available"] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ["EUR", "GBP", "USD"]: return float( truncate( float( df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float( df[df['currency'] == currency] ['available'].values[0]), 4)) else: time.sleep(5) trycnt += 1 else: return 0.0 else: # return dummy balances if currency == "": # retrieve all balances return self.balance else: # replace QUOTE and BASE placeholders if currency in ["EUR", "GBP", "USD"]: self.balance = self.balance.replace("QUOTE", currency) elif currency in ["BCH", "BTC", "ETH", "LTC", "XLM"]: self.balance = self.balance.replace("BASE", currency) if (self.balance.currency[self.balance.currency.isin( [currency])].empty == True): self.balance.loc[len( self.balance)] = [currency, 0, 0, 0] # retrieve balance of specified currency df = self.balance df_filtered = df[df["currency"] == currency]["available"] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) if currency in ["EUR", "GBP", "USD"]: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 2)) else: return float( truncate( float(df[df['currency'] == currency] ['available'].values[0]), 4)) else: # dummy account if currency == "": # retrieve all balances return self.balance else: # retrieve balance of specified currency df = self.balance df_filtered = df[df["currency"] == currency]["available"] if len(df_filtered) == 0: # return nil balance if no positive balance was found return 0.0 else: # return balance of specified currency (if positive) return float( df[df["currency"] == currency]["available"].values[0])
def getLastBuy(self) -> dict: """Retrieves the last exchange buy order and returns a dictionary""" try: if self.exchange == 'coinbasepro': api = CBAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIPassphrase(), self.getAPIURL()) orders = api.getOrders(self.getMarket(), '', 'done') if len(orders) == 0: return None last_order = orders.tail(1) if last_order['action'].values[0] != 'buy': return None return { 'side': 'buy', 'market': self.getMarket(), 'size': float(last_order['size']), 'filled': float(last_order['filled']), 'price': float(last_order['price']), 'fee': float(last_order['fees']), 'date': str( pd.DatetimeIndex( pd.to_datetime( last_order['created_at']).dt.strftime( '%Y-%m-%dT%H:%M:%S.%Z'))[0]) } elif self.exchange == 'binance': api = BAuthAPI(self.getAPIKey(), self.getAPISecret(), self.getAPIURL()) orders = api.getOrders(self.getMarket()) if len(orders) == 0: return None last_order = orders.tail(1) if last_order['action'].values[0] != 'buy': return None return { 'side': 'buy', 'market': self.getMarket(), 'size': float(last_order['size']), 'filled': float(last_order['filled']), 'price': float(last_order['price']), 'fees': float(last_order['size'] * 0.001), 'date': str( pd.DatetimeIndex( pd.to_datetime( last_order['created_at']).dt.strftime( '%Y-%m-%dT%H:%M:%S.%Z'))[0]) } else: return None except Exception: return None
from models.PyCryptoBot import PyCryptoBot from models.exchange.binance import AuthAPI as BAuthAPI from models.exchange.coinbase_pro import AuthAPI as CAuthAPI # Coinbase Pro fees app = PyCryptoBot(exchange='coinbasepro') api = CAuthAPI(app.getAPIKey(), app.getAPISecret(), app.getAPIPassphrase(), app.getAPIURL()) #print (api.getTakerFee()) #print (api.getTakerFee('BTC-GBP')) #print (api.getMakerFee()) #print (api.getMakerFee('BTC-GBP')) #print (api.getFees('BTCGBP')) #print (api.getFees()) print(app.getMakerFee()) print(app.getTakerFee()) # Binance fees app = PyCryptoBot(exchange='binance') api = BAuthAPI(app.getAPIKey(), app.getAPISecret(), app.getAPIURL()) #print (api.getTakerFee()) #print (api.getTakerFee('BTCGBP')) #print (api.getMakerFee()) #print (api.getMakerFee('BTCGBP')) #print (api.getFees('BTCGBP')) #print (api.getFees()) print(app.getMakerFee()) print(app.getTakerFee())