def main(): console.log('Starting...') exchanges['bitstamp'] = Exchange( ccxt.bitstamp(config=config.bitstamp.to_dict())) exchanges['binance'] = Exchange( ccxt.binance(config=config.binance.to_dict())) exchanges['bittrex'] = Exchange( ccxt.bittrex(config=config.bittrex.to_dict())) exchanges['cryptopia'] = Exchange( ccxt.cryptopia(config=config.cryptopia.to_dict())) exchanges['hitbtc'] = Exchange( ccxt.hitbtc2(config=config.hitbtc.to_dict())) telebot.add_handler( telegram.CommandHandler(command='balance', callback=TelegramCommands.get_balance)) telebot.add_handler( telegram.CommandHandler(command='start', callback=TelegramCommands.start)) telebot.add_handler( telegram.CommandHandler(command='help', callback=TelegramCommands.show_help)) telebot.start() console.log('Ready...') telebot.idle()
def add_price_table(exchange="binance"): ## API Key and Secret Key api = "" secret = "" exchange_obj = None if exchange == "binance": exchange_obj = ccxt.binance({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bidPrice']) ask_price = float(cur_data['info']['askPrice']) cur_time = cur_data['timestamp'] elif exchange == "cryptopia": exchange_obj = ccxt.cryptopia({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['BidPrice']) ask_price = float(cur_data['info']['AskPrice']) cur_time = cur_data['timestamp'] elif exchange == "bittrex": exchange_obj = ccxt.bittrex({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['Bid']) ask_price = float(cur_data['info']['Ask']) cur_time = cur_data['timestamp'] elif exchange == "hitbtc": exchange_obj = ccxt.hitbtc2({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bid']) ask_price = float(cur_data['info']['ask']) cur_time = cur_data['timestamp'] else: print("Unsupported Exchange platform") return
def __init__(self): self.hitbtc = ccxt.hitbtc2({'nonce': ccxt.hitbtc2.milliseconds}) if ( settings['hitbtc_exporter'].get('api_key') and settings['hitbtc_exporter'].get('api_secret') ): self.hitbtc.apiKey = settings['hitbtc_exporter'].get('api_key') self.hitbtc.secret = settings['hitbtc_exporter'].get('api_secret') self.hasApiCredentials = True if settings['hitbtc_exporter'].get('uid'): self.hitbtc.uid = settings['hitbtc_exporter'].get('uid') self.hasApiCredentials = True
def get_hitbtc_static(file): with open(file, 'a') as csvFile: csvwriter = csv.writer(csvFile) hitbtc = ccxt.hitbtc2() for i in hitbtc.fetch_markets(): if i['symbol'] in ['BTC/USDT', 'ETH/USDT', 'BCH/USDT']: uid = i['symbol'].replace('/', '_') + '-hitbtc' csvwriter.writerow([ uid, 'Hitbtc', i['id'], i['info']['tickSize'], '1', i['limits']['amount']['min'], i['limits']['amount']['max'], i['limits']['price']['min'], i['limits']['price']['max'], i['precision']['amount'], i['precision']['price'], i['taker'] * 10000, i['maker'] * 10000, 0, 0, 'cryptocurrency' ])
def setup_clients(self): self.exchanges['Bittrex'] = ccxt.bittrex({ 'apiKey': self.meta['Bittrex']['public'], 'secret': self.meta['Bittrex']['secret'], }) self.exchanges['Poloniex'] = ccxt.poloniex({ 'apiKey': self.meta['Poloniex']['public'], 'secret': self.meta['Poloniex']['secret'], }) self.exchanges['YoBit'] = ccxt.yobit({ 'apiKey': self.meta['YoBit']['public'], 'secret': self.meta['YoBit']['secret'], }) self.exchanges['HitBTC'] = ccxt.hitbtc2({ 'apiKey': self.meta['HitBTC']['public'], 'secret': self.meta['HitBTC']['secret'], }) self.exchanges['Tidex'] = ccxt.tidex({ 'apiKey': self.meta['Tidex']['public'], 'secret': self.meta['Tidex']['secret'], }) self.exchanges['Binance'] = ccxt.binance({ 'options': { 'adjustForTimeDifference': True }, 'apiKey': self.meta['Binance']['public'], 'secret': self.meta['Binance']['secret'], }) self.exchanges['Bitfinex'] = ccxt.bitfinex({ 'apiKey': self.meta['Bitfinex']['public'], 'secret': self.meta['Bitfinex']['secret'], })
def init_exchange(): # ���������� ���� � ����������� with open('keys.txt', 'r', encoding='utf-8') as fl: keys = json.load(fl) # ������������ � ����� # ���� � ������ ��� �������� ���������� �����, �� ���������� � HitBTC if not 'marketplace' in keys: try: exchange = ccxt.hitbtc2({ "apiKey": keys['apiKey'], "secret": keys['secretKey'], # "enableRateLimit": True, # "verbose": True, # "password": password, }) except Exception as e: print("Connection Error 1") else: try: exchange = eval( 'ccxt.%s({\'apiKey\':\"%s\",\'secret\':\"%s\"})' % (keys['marketplace'], keys['apiKey'], keys['secretKey'])) except Exception as e: print("Connection Error 2") # ������� ��������� ����������� ��������� try: # ������ ��������� ��� MARKETS = keys['markets'] # MARKETS = ['EOS/ETH'] if 'tradeCount' in keys: print(1) # ����������� ������ ��� ��������� � ������ currency (��������, ETH) balance = get_positive_accounts( exchange.fetch_balance()[keys['currency']])['free'] print(2) CAN_SPEND = keys[ 'tradeCount'] # ������� ������ ������� � ��� % �� ������������� ������� REFRESH = False # if CAN_SPEND > balance: # raise IOError("Trading account less for this trade!") print(3) else: balance = get_positive_accounts( exchange.fetch_balance()[keys['currency']])['free'] CAN_SPEND = float(keys['percent']) * balance REFRESH = True print(MARKETS) MARKUP = float( keys['markup']) # 0.001 = 0.1% �������� ������� ������� �� ������ STOCK_FEE = float(keys['fee']) # ����� �������� ����� ����� ORDER_LIFE_TIME = float( keys['order_time'] ) # ����� ��� ������ �������������� ������ �� ������� 0.5 = 30 ���. pprint(""" Can Spend - %0.8f %s Fee: %0.8f, Markup: %0.8f, Balance: %0.8f %s """ % (CAN_SPEND, keys['currency'], keys['fee'], keys['markup'], CAN_SPEND, keys['currency'])) except Exception as e: print("Connection Error 3") return exchange, MARKETS, CAN_SPEND, MARKUP, STOCK_FEE, ORDER_LIFE_TIME, keys, REFRESH
def run_Indicator_MACD_bot(bot, exchange): # Bot parmeters user_id = bot[5] interval = bot[35] can_interval = get_candle_interval(interval) bot_id = str(bot[0]) bot_name = str(bot[1]) bot_type = str(bot[2]) base_currency = str(bot[8]) selected_coin = str(bot[9]) coin_pair = selected_coin + "/" + base_currency buy_higher = str(bot[11]) sell_cheaper = str(bot[12]) profit = float(bot[15]) stop_loss = float(bot[16]) stay_profitable = str(bot[14]) double_fee = str(bot[13]) trading_volume = float(bot[10]) slow_period = int(bot[26]) fast_period = float(bot[27]) signal_period = float(bot[28]) # Declare local variables indicator_profit = 0.0 sum_plus = 0.0 sum_minus = 0.0 coin_balance = 0.0 base_balance = 0.0 last_buy_price = 0.0 last_sell_price = 0.0 bid_price = 0.0 ask_price = 0.0 temp_data = [] value_dif = [] hist_data = [] cur_data = [] total_balance = [] middle_price = 0.0 # average value corresponding the p upper_price = 0.0 lower_price = 0.0 bb_temp = [] avg = 0 stand_dev = 0.0 bb_index = 0 # not used? cur_time = "" order_type = "" order_status = "" buy_time = "" sell_time = "" buy_price = 0.0 sell_price = 0.0 buy_fee = 0.0 sell_fee = 0.0 log_str = "" # Get API key and secret key query_conn.execute( " select api_key, secret from exchange_info where user_id=%s and exchange=%s", (user_id, exchange)) key_data = query_conn.fetchone() api = key_data[0] secret = key_data[1] db_conn.commit() exchange_obj = None if exchange == "binance": exchange_obj = ccxt.binance({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bidPrice']) ask_price = float(cur_data['info']['askPrice']) cur_time = cur_data['timestamp'] elif exchange == "cryptopia": exchange_obj = ccxt.cryptopia({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['BidPrice']) ask_price = float(cur_data['info']['AskPrice']) cur_time = cur_data['timestamp'] elif exchange == "bittrex": exchange_obj = ccxt.bittrex({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['Bid']) ask_price = float(cur_data['info']['Ask']) cur_time = cur_data['timestamp'] elif exchange == "hitbtc": exchange_obj = ccxt.hitbtc2({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bid']) ask_price = float(cur_data['info']['ask']) cur_time = cur_data['timestamp'] else: print("Unsupported Exchange platform") return
def run_Indicator_BB_bot(bot, exchange="binance"): # Bot parmeters user_id = bot[5] interval = bot[35] can_interval = get_candle_interval(interval) bot_id = str(bot[0]) bot_name = str(bot[1]) bot_type = str(bot[2]) base_currency = str(bot[8]) selected_coin = str(bot[9]) coin_pair = selected_coin + "/" + base_currency buy_higher = str(bot[11]) sell_cheaper = str(bot[12]) profit = float(bot[15]) stop_loss = float(bot[16]) stay_profitable = str(bot[14]) double_fee = str(bot[13]) #trading_volume = float(bot[10]) period = int(bot[29]) upper_dev = float(bot[30]) lower_dev = float(bot[31]) # Declare local variables indicator_profit = 0.0 sum_plus = 0.0 sum_minus = 0.0 trading_volume = 0.0 coin_balance = 0.0 base_balance = 0.0 last_buy_price = 0.0 last_sell_price = 0.0 bid_price = 0.0 ask_price = 0.0 temp_data = [] value_dif = [] hist_data = [] bid_hist_data = [] ask_hist_data = [] sell_order_book = [] buy_order_book = [] cur_data = [] total_balance = [] middle_price = 0.0 # average value corresponding the p upper_price = 0.0 lower_price = 0.0 bb_temp = [] avg = 0 stand_dev = 0.0 bb_index = 0 # not used? cur_time = "" order_type = "" order_status = "" buy_time = "" sell_time = "" buy_price = 0.0 sell_price = 0.0 buy_fee = 0.0 sell_fee = 0.0 log_str = "" # Get API key and secret key query_conn.execute( " select api_key, secret from exchange_info where user_id=%s and exchange=%s", (user_id, exchange)) key_data = query_conn.fetchone() api = key_data[0] secret = key_data[1] db_conn.commit() exchange_obj = None if exchange == "binance": exchange_obj = ccxt.binance({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bidPrice']) ask_price = float(cur_data['info']['askPrice']) cur_time = cur_data['timestamp'] elif exchange == "cryptopia": exchange_obj = ccxt.cryptopia({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['BidPrice']) ask_price = float(cur_data['info']['AskPrice']) cur_time = cur_data['timestamp'] elif exchange == "bittrex": exchange_obj = ccxt.bittrex({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['Bid']) ask_price = float(cur_data['info']['Ask']) cur_time = cur_data['timestamp'] elif exchange == "hitbtc": exchange_obj = ccxt.hitbtc2({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bid']) ask_price = float(cur_data['info']['ask']) cur_time = cur_data['timestamp'] else: print("Unsupported Exchange platform") return ######### Get historical data from exchnage exchange_obj.has['fetchOHLCV'] = 'emulated' hist_data = exchange_obj.fetch_ohlcv(coin_pair, interval, limit=period - 1) total_balance = exchange_obj.fetch_balance() base_balance = float(total_balance[base_currency]['total']) coin_balance = float(total_balance[selected_coin]['total']) #buy_t_volume = min(base_balance/ask_price, trading_volume) #sell_t_volume = min(coin_balance, trading_volume) buy_exchange_fee = exchange_obj.calculate_fee(coin_pair, 'market', 'buy', 1, ask_price, 'maker') buy_fee = round(ask_price * float(buy_exchange_fee['rate']), 8) # is this right, it is necessary to multiply ask_price sell_exchange_fee = exchange_obj.calculate_fee(coin_pair, 'market', 'sell', 1, bid_price, 'maker') sell_fee = round(bid_price * float(sell_exchange_fee['rate']), 8) #hist_data.append([cur_time, 0, 0, 0, bid_price, 0]) #for i in range(0, period): # bb_temp.append(hist_data[i][4]) #avg = np.mean(bb_temp) #stand_dev = np.std(bb_temp) #upper_price = round(avg + stand_dev * upper_dev, 8) #lower_price = round(avg + stand_dev * lower_dev, 8) query_conn.execute( "select buy_price from trading_history where bot_id=%s and buy_price<>'0' order by absID desc", (bot_id, )) temp = query_conn.fetchone() if query_conn.rowcount: last_buy_price = temp[0] else: last_buy_price = 0 db_conn.commit() query_conn.execute( "select sell_price from trading_history where bot_id=%s and sell_price<>'0' order by absID desc", (bot_id, )) temp = query_conn.fetchone() if query_conn.rowcount: last_sell_price = temp[0] else: last_sell_price = 0 db_conn.commit() query_conn.execute( "select order_type, buy_price, sell_price from trading_history where bot_id=%s and order_status=%s", (bot_id, 'create')) trans_data = query_conn.fetchall() db_conn.commit() t = datetime.datetime.fromtimestamp(cur_time / 1000) ######### Get historical data from database query_conn.execute( "select bid_price, ask_price from coin_price where exchange=%s and coin_pair=%s and date=%s", (exchange, coin_pair, t[:10])) temp_data = query_conn.fetchall() db_conn.commit() temp_bid_data = str(temp_data[0][0]).split(",") temp_ask_data = str(temp_data[0][1]) if len(temp_bid_data) < (period - 1): return else: for i in range(len(temp_bid_data) - period + 1, period): bid_hist_data.append(temp_bid_data[i].split("-")[1]) ask_hist_data.append(temp_ask_data[i].split("-")[1]) bid_hist_data.append(bid_price) ask_hist_data.append(ask_price) if len(trans_data) > 0: # if there is an order with the create status order_type = trans_data[0][0] buy_price = float(trans_data[0][1]) sell_price = float(trans_data[0][2]) if order_type == "buy": #### add bid_price for selling with buy order #hist_data.append([cur_time, 0, 0, 0, bid_price, 0]) #for i in range(0, period): # bb_temp.append(hist_data[i][4]) avg = np.mean(bid_hist_data) #avg = np.mean(bb_temp) stand_dev = np.std(bid_hist_data) #stand_dev = np.std(bb_temp) upper_price = round(avg + stand_dev * upper_dev, 8) lower_price = round(avg + stand_dev * lower_dev, 8) sell_order_book = exchange_obj.fetch_order_book(coin_pair)['bids'] for order in sell_order_book: if order[0] >= bid_price: trading_volume += float(order[1]) else: break sell_t_volume = min(coin_balance, trading_volume) log_str = str( t ) + ': ' + 'compare: sell with buy ' + coin_pair + '(e_price=' + str( bid_price ) + ', bb_price=' + str(upper_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ')\n' add_bot_log(log_str) if bid_price >= upper_price: #if coin_balance >= trading_volume * 0.95: if coin_balance > 0: log_str = str( t ) + ': ' + 'parameter: sell with buy ' + coin_pair + '(e_price=' + str( bid_price ) + ', bb_price=' + str(upper_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' add_bot_log(log_str) eval_result = eval_bb_trading_cond( bot_id, "upper", bid_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, sell_t_volume, stay_profitable, double_fee, sell_fee, t) if eval_result == "close": # why is this return value close? try: exchange_obj.create_market_sell_order( coin_pair, sell_t_volume) log_str = str( t ) + ': ' + 'Sell ' + coin_pair + '(sell_price=' + str( bid_price) + ', bot_price=' + str( upper_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating sell order in sell with buy\n" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in sell with buy\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "coin balance is less than trading volume in sell with buy\n" ) else: if bid_price >= (buy_price + float(profit) * buy_price / 100): eval_result = eval_bb_trading_cond( bot_id, "upper", bid_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, sell_t_volume, stay_profitable, double_fee, sell_fee, t) if eval_result == "close": # why is this return value close? try: exchange_obj.create_market_sell_order( coin_pair, sell_t_volume) log_str = str( t ) + ': ' + 'Sell ' + coin_pair + '(sell_price=' + str( bid_price) + ', bot_price=' + str( upper_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating sell order in sell with buy\n" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in sell with buy\n") else: if bid_price <= (buy_price - float(stop_loss) * buy_price / 100): try: exchange_obj.create_market_sell_order( coin_pair, sell_t_volume) log_str = str( t ) + ': ' + 'Sell ' + coin_pair + ' for stop_loss (sell_price=' + str( bid_price) + ', bot_price=' + str( upper_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating sell order in sell with buy\n" else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "bid price is less than upper price in sell with buy\n" ) elif order_type == "sell": ### add ask_price to history data for buying with sell order #hist_data.append([cur_time, 0, 0, 0, ask_price, 0]) #for i in range(0, period): # bb_temp.append(hist_data[i][4]) avg = np.mean(ask_hist_data) #avg = np.mean(bb_temp) stand_dev = np.std(ask_hist_data) #stand_dev = np.std(bb_temp) upper_price = round(avg + stand_dev * upper_dev, 8) lower_price = round(avg + stand_dev * lower_dev, 8) buy_order_book = exchange_obj.fetch_order_book(coin_pair)['asks'] for order in buy_order_book: if order[0] <= ask_price: trading_volume += float(order[1]) else: break buy_t_volume = min(base_balance, trading_volume * ask_price) log_str = str( t ) + ': ' + 'compare: buy with sell ' + coin_pair + '(e_price=' + str( ask_price ) + ', bb_price=' + str(lower_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( total_balance[selected_coin] ['total']) + ' ' + base_currency + '=' + str( total_balance[base_currency]['total']) + ')\n' add_bot_log(log_str) if ask_price <= lower_price: #if base_balance >= 0.95 * trading_volume * ask_price: if base_balance > 0: log_str = str( t ) + ': ' + 'parameter: buy with sell ' + coin_pair + '(e_price=' + str( ask_price ) + ', bb_price=' + str(lower_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_price ) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str(buy_fee) + ')\n' add_bot_log(log_str) eval_result = eval_bb_trading_cond( bot_id, 'lower', ask_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, buy_t_volume, stay_profitable, double_fee, buy_fee, t) if eval_result == "close": try: exchange_obj.create_market_buy_order( coin_pair, buy_t_volume) log_str = str( t ) + ': ' + 'Buy ' + coin_pair + '(e_price=' + str( ask_price) + ', bb_price=' + str( lower_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( buy_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating buy order\n" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in buy with sell\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "base balance is less than trading volume in buy with sell\n" ) else: if ask_price <= (sell_price - float(profit) * sell_price / 100): print("take profit success") eval_result = eval_bb_trading_cond( bot_id, 'lower', ask_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, buy_t_volume, stay_profitable, double_fee, buy_fee, t) if eval_result == "close": try: exchange_obj.create_market_buy_order( coin_pair, buy_t_volume) log_str = str( t ) + ': ' + 'Buy ' + coin_pair + '(e_price=' + str( ask_price) + ', bb_price=' + str( lower_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( buy_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating buy order\n" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in buy with sell\n") else: if ask_price >= (sell_price + float(stop_loss) * sell_price / 100): try: exchange_obj.create_market_buy_order( coin_pair, buy_t_volume) log_str = str( t ) + ': ' + 'Buy ' + coin_pair + '(e_price=' + str( ask_price) + ', bb_price=' + str( lower_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( buy_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating buy order\n" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "ask price is greater than lower price in buy with sell\n" ) else: # if there is no order with the create status if base_balance >= 0.95 * trading_volume * ask_price: ### add ask_price to history data for buying without any created order # hist_data.append([cur_time, 0, 0, 0, ask_price, 0]) # for i in range(0, period): # bb_temp.append(hist_data[i][4]) avg = np.mean(ask_hist_data) # avg = np.mean(bb_temp) stand_dev = np.std(ask_hist_data) # stand_dev = np.std(bb_temp) upper_price = round(avg + stand_dev * upper_dev, 8) lower_price = round(avg + stand_dev * lower_dev, 8) log_str = str( t ) + ': ' + 'compare: buy without none ' + coin_pair + '(e_price=' + str( ask_price ) + ', bb_price=' + str(lower_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( total_balance[selected_coin] ['total']) + ' ' + base_currency + '=' + str( total_balance[base_currency]['total']) + ')\n' add_bot_log(log_str) if ask_price <= lower_price: log_str = str( t ) + ': ' + 'parameter: buy without none ' + coin_pair + '(e_price=' + str( ask_price ) + ', bb_price=' + str(lower_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str(buy_fee) + ')\n' add_bot_log(log_str) eval_result = eval_bb_trading_cond(bot_id, "lower", ask_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, buy_t_volume, stay_profitable, double_fee, buy_fee, t) if eval_result == "open": try: exchange_obj.create_market_buy_order( coin_pair, buy_t_volume) log_str = str( t) + ': ' + 'Buy ' + coin_pair + '(e_price=' + str( ask_price) + ', bb_price=' + str( lower_price ) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( buy_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating buy order" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in buy with none\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "ask price is greater than lower price in buy with none\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "base balance is less than trading volume in sell with none\n") if coin_balance >= 0.95 * trading_volume: ### add bid price to history data for selling without any created order # hist_data.append([cur_time, 0, 0, 0, bid_price, 0]) # for i in range(0, period): # bb_temp.append(hist_data[i][4]) avg = np.mean(bid_hist_data) # avg = np.mean(bb_temp) stand_dev = np.std(bid_hist_data) # stand_dev = np.std(bb_temp) upper_price = round(avg + stand_dev * upper_dev, 8) lower_price = round(avg + stand_dev * lower_dev, 8) log_str = str( t ) + ': ' + 'compare: sell without none ' + coin_pair + '(e_price=' + str( bid_price ) + ', bb_price=' + str(upper_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ')\n' add_bot_log(log_str) if bid_price >= upper_price: log_str = str( t ) + ': ' + 'compare: sell without none ' + coin_pair + '(e_price=' + str( bid_price ) + ', bb_price=' + str(upper_price) + ', bb_u_dev=' + str( upper_dev) + ', bb_l_dev=' + str( lower_dev) + ', balance:' + selected_coin + '=' + str( coin_balance) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' add_bot_log(log_str) eval_result = eval_bb_trading_cond(bot_id, "upper", bid_price, last_buy_price, last_sell_price, buy_higher, sell_cheaper, sell_t_volume, stay_profitable, double_fee, sell_fee, t) if eval_result == "open": try: exchange_obj.create_market_sell_order( coin_pair, sell_t_volume) log_str = str( t ) + ': ' + 'Sell ' + coin_pair + '(e_price=' + str( bid_price) + ', bb_price=' + str( upper_price) + ', bb_u_dev=' + str( upper_dev ) + ', bb_l_dev=' + str( lower_dev ) + ', balance:' + selected_coin + '=' + str( total_balance[selected_coin]['total'] ) + ' ' + base_currency + '=' + str( total_balance[base_currency]['total'] ) + ', balance:' + selected_coin + '=' + str( coin_balance ) + ' ' + base_currency + '=' + str( base_balance) + ', fee=' + str( sell_fee) + ')\n' except: log_str = str( t ) + ': ' + coin_pair + ': ' + exchange + "API Error occurred while creating sell order" add_bot_log(log_str) else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "parameter compare failed in sell with none\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "bid price is less than upper price in sell with none\n") else: add_bot_log( str(t) + ': ' + coin_pair + ': ' + "coin balance is less than trading volume in sell with none\n")
TP_LEVEL = 500 SL2_LEVEL = 70 SL_OFFSET = 70 # TRADE SIZE TRADE_SIZE = 200 # PERCENTAGE VOL ABOVE AVG pavg = 100 exchanges = { 'binance': binance(), 'bitfinex': bitfinex(), 'coinbase': coinbasepro(), 'bitmex': bitmex(), 'hitbtc': hitbtc2(), 'kraken': kraken(), 'bittrex': bittrex(), 'huobi': huobipro() } symbols = { 'binance': 'BTC/USDC', 'bitfinex': 'BTC/USD', 'coinbase': 'BTC/USD', 'bitmex': 'BTC/USD', 'hitbtc': 'BTC/USDT', 'kraken': 'BTC/USD', 'bittrex': 'BTC/USD', 'huobi': 'BTC/USDT' }
import sys import ccxt import numpy as np import time import datetime from pytz import timezone import cry_arb_evaluator import json dash = '-' * 25 space = ' ' * 2 tz = timezone('EST') kraken = ccxt.kraken({'enableRateLimit': True}) exmo = ccxt.exmo({'enableRateLimit': True}) binance = ccxt.binance({'enableRateLimit': True}) hitbtc = ccxt.hitbtc2({'enableRateLimit': True}) coinbasepro = ccxt.coinbasepro({ 'enableRateLimit': True, }) gemini = ccxt.gemini({ 'enableRateLimit': True, }) bitfinex = ccxt.bitfinex({ 'enableRateLimit': True, }) livecoin = ccxt.livecoin({ 'enableRateLimit': True, }) kucoin = ccxt.kucoin({ 'enableRateLimit': True, })
# (ccxt.bitfinex({ # 'apiKey': BITFINEX_KEY, # 'secret': BITFINEX_SECRET, # }), 'https://www.bitfinex.com/trading/{0}{1}'), # # 2. Bithumb # (ccxt.bithumb(), 'https://www.bithumb.com/trade/order/{0}'), # 3. Bittrex (ccxt.bittrex(), 'https://bittrex.com/Market/Index?MarketName={1}-{0}'), # 4. Poloniex (ccxt.poloniex(), 'https://poloniex.com/exchange#{1}_{0}'), # # 5. GDAX # (ccxt.gdax(), 'https://www.gdax.com/trade/{0}-{1}'), # # 7. Kraken # (ccxt.kraken(), 'https://www.kraken.com/charts'), # 8. HitBTC (ccxt.hitbtc2(), 'https://hitbtc.com/exchange/{0}-to-{1}'), # # 9. Bitstamp (sometimes raises HTTPError 404: NOT FOUND) # (ccxt.bitstamp(), 'https://www.bitstamp.net/'), # 10. bitFlyer (need apiKey and secret) # (ccxt.bitflyer(), 'https://lightning.bitflyer.jp/trade/{0}{1}'), # # 12. Gemini # (ccxt.gemini(), 'https://gemini.com/marketplace/'), # # 14. Binance # (ccxt.binance({ # 'apiKey': BINANCE_KEY, # 'secret': BINANCE_SECRET, # }), 'https://www.binance.com/trade.html?symbol={0}_{1}'), # # 16. WEX # (ccxt.wex(), 'https://wex.nz/exchange/{0}_{1}'), # # 21. CEX.IO # (ccxt.cex(), 'https://cex.io/{0}-{1}'),
# API KEYS ZONE BITMEX_API_KEY = '' BITMEX_API_SECRET = '' # SL & TP LEVELS SL_LEVEL = 200 TP_LEVEL = 500 SL2_LEVEL = 100 SL_OFFSET = 60 # TRADE SIZE TRADE_SIZE = 100 exchanges = {'binance': binance(), 'bitstamp': bitstamp(), 'bitfinex': bitfinex(), 'coinbase': coinbasepro(), 'bitmex': bitmex(), 'hitbtc': hitbtc2(), 'kraken': kraken(), 'bittrex': bittrex(), 'huobi': huobipro()} symbols = {'binance': 'BTC/USDC', 'bitstamp': 'BTC/USD', 'bitfinex': 'BTC/USD', 'coinbase': 'BTC/USD', 'bitmex': 'BTC/USD', 'hitbtc': 'BTC/USDT', 'kraken': 'BTC/USD', 'bittrex': 'BTC/USD', 'huobi': 'BTC/USDT'} btmx = bitmex({'apiKey': BITMEX_API_KEY, 'secret': BITMEX_API_SECRET}) new_signal = False hour_closed = False # uncomment for testnet # if 'test' in btmx.urls: # btmx.urls['api'] = btmx.urls['test'] # ←----- switch the base URL to testnet # exchanges['bitmex'].urls['api'] = exchanges['bitmex'].urls['test']
STAT_CONSUMER = 'https://cryptodaemon.cloud/bot_api/stat/' # emulation FAKE_DEPOSIT = 2 # dirs BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # keys API_KEYS = {'hitbtc': dict(api='aeac732a33236d840e4beccfced63754', secret='17e70f8a123e2b90fd0440c0deb6f3a6')} # exchanges SUPPORTED_EXCHANGES = dict(hitbtc=hitbtc2, poloniex=poloniex, exmo=exmo) DEFAULT_EXCHANGE = hitbtc2({ "apiKey": API_KEYS['hitbtc']['api'], "secret": API_KEYS['hitbtc']['secret'], "enableRateLimit": True, }) DEFAULT_EXCH_CLASS = DEFAULT_EXCHANGE.__class__ # profit policies FULL_REINVEST = 'full-reinvest' HALF_REINVEST = 'half-reinvest' FULL_TAKE = 'full-take' # currency BASE_TICKER = 'BTC' USD = 'USD' # strategies
root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath("New.txt")))) sys.path.append(root + '/python') import ccxt # noqa: E402 ############################################## print("My HitBTC") public_key = "42555f6f72ff2b5f5a7a1b0a52cafd17" secret = "e077ccce0034bbe610ffa1068630bdac" exchange = ccxt.hitbtc2({ "apiKey": public_key, "secret": secret, # "verbose": True, #"password": password, }) ##Балансы #ex = exchange.create_order("BCH/ETH", 'limit','sell',0.22, 2.05) trading_balance = exchange.fetch_balance() account_balance = exchange.fetch_balance({'type': 'account'}) print(get_positive_accounts(exchange.fetch_balance()['ETH'])['free']) pprint('Trading balance:') print(get_positive_accounts(trading_balance['free'])) pprint('Account balance:') pprint(get_positive_accounts(account_balance['total'])) pprint(exchange.fetch_open_orders())
extCoinBalance = config.get('extCoinBalance', 0) checkInterval = config.get('checkInterval', 30) initialSellPrice = config.get('initialSellPrice', 0) tradeAmount = config.get('tradeAmount', 0) slackChannel = config['slackChannel'] slackToken = config['slackToken'] # global / constants token = currency + "/" + trade volumePercent = volumePercent * .01 sellValuePercent = sellValuePercent * .01 buyValuePercent = buyValuePercent * .01 buyDifference = buyDifference * .01 exchange = ccxt.hitbtc2({ "apiKey": apiKey, "secret": apiSecret, "enableRateLimit": True, }) def get_token_balance(): balance = exchange.fetch_balance() currencies = list(balance.keys()) for c in currencies: if currency in c: return (balance[c]['free']) def determine_sell_amount(balance): return round(balance * volumePercent,-3) def determine_buy_amount(balance): amount = round(balance * volumePercent * (1 / (1 - volumePercent) * 1 + buyDifference), -3)
import ccxt # noqa: E402 def get_positive_accounts(balance): result = {} currencies = list(balance.keys()) for currency in currencies: if balance[currency] and balance[currency] > 0: result[currency] = balance[currency] return result exchange = ccxt.hitbtc2({ "apiKey": "a34ca826b430bdfcca969241b0f7bd2d", "secret": "7b28d6b17aea18ae39903add0dae048a", "enableRateLimit": True, }) trading_balance = exchange.fetch_balance() account_balance = exchange.fetch_balance({'type': 'account'}) pprint('Trading balance:') pprint(get_positive_accounts(trading_balance['total'])) pprint('Account balance:') pprint(get_positive_accounts(account_balance['total'])) withdraw = exchange.withdraw('ETH', 0.01, '0x811DCfeb6dC0b9ed825808B6B060Ca469b83fB81')
import ccxt # noqa: E402 def get_positive_accounts(balance): result = {} currencies = list(balance.keys()) for currency in currencies: if balance[currency] and balance[currency] > 0: result[currency] = balance[currency] return result exchange = ccxt.hitbtc2({ "apiKey": "a34ca826b430bdfcca969241b0f7bd2d", "secret": "7b28d6b17aea18ae39903add0dae048a", "enableRateLimit": True, }) trading_balance = exchange.fetch_balance() account_balance = exchange.fetch_balance({'type': 'account'}) pprint('Trading balance:') pprint(get_positive_accounts(trading_balance['total'])) pprint('Account balance:') pprint(get_positive_accounts(account_balance['total'])) withdraw = exchange.withdraw('ETH', 0.01, '0x811DCfeb6dC0b9ed825808B6B060Ca469b83fB81') pprint('Withdraw:')
'exchangeName': "bitstamp", 'database': bitstamp_db }) btcturk = ccxt.btcturk({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "btcturk", 'database': btcturk_db }) hitbtc = ccxt.hitbtc2({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "hitbtc" , 'database': hitbtc_db }) bitbay = ccxt.bitbay({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "bitbay", 'database': bitbay_db }) bl3p = ccxt.bl3p({ 'rateLimit': 3000, 'enableRateLimit': True,
ccxt.dsx(), ccxt.ethfinex(), ccxt.exmo(), ccxt.exx(), ccxt.flowbtc(), ccxt.foxbit(), ccxt.fybse(), ccxt.fybsg(), ccxt.gatecoin(), ccxt.gateio(), ccxt.gdax(), ccxt.gemini(), ccxt.getbtc(), ccxt.hadax(), ccxt.hitbtc(), ccxt.hitbtc2(), ccxt.huobi(), ccxt.huobicny(), ccxt.huobipro(), ccxt.ice3x(), ccxt.independentreserve(), ccxt.indodax(), ccxt.itbit(), ccxt.jubi(), ccxt.kraken(), ccxt.kucoin(), ccxt.kuna(), ccxt.lakebtc(), ccxt.lbank(), ccxt.liqui(), ccxt.livecoin(),