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 get_market(market=OKEX): mk = ccxt.okcoinusd() if market == HUOBI: mk = ccxt.huobipro() if market == CRY: mk = ccxt.cryptopia() if market == BIN: mk = ccxt.binance() if market == PLX: mk = ccxt.poloniex() return mk
def getUSDPrice(coin, btcusdprice): url = "https://min-api.cryptocompare.com/data/price?fsym=" + coin + "&tsyms=USD" r = requests.get(url) if r.status_code == 404: cryptopia = ccxt.cryptopia() cryptopia_markets = cryptopia.load_markets() data = cryptopia.fetch_ticker(coin + '/BTC') return btcusdprice * data["info"]["LastPrice"] else: data = r.json() return data["USD"]
def get_exchange_list(): bittrex_exchange = ccxt.bittrex() binance_exchange = ccxt.binance() kucoin_exchange = ccxt.kucoin() huobiPro_exchange = ccxt.huobipro() cryptopia_exchange = ccxt.cryptopia() bitmex_exchange = ccxt.bitmex() list_of_exchanges = [ bittrex_exchange, binance_exchange, kucoin_exchange, huobiPro_exchange, cryptopia_exchange ] return list_of_exchanges
def exchangeObject(exchange_in): exchanges = [ccxt.acx(),ccxt.bitbay(),ccxt.bitfinex(),ccxt.bitflyer(),ccxt.bithumb(),ccxt.bitlish(),ccxt.bitmarket(),ccxt.bitmex(),ccxt.bitso(), ccxt.bitstamp(),ccxt.bitstamp1(),ccxt.bittrex(),ccxt.bl3p(),ccxt.bleutrade(),ccxt.btcbox(),ccxt.btcchina(),ccxt.btcexchange(),ccxt.btcmarkets(),ccxt.btctradeua(),ccxt.btcturk(), ccxt.btcx(),ccxt.bxinth(),ccxt.ccex(),ccxt.cex(),ccxt.chbtc(),ccxt.chilebit(),ccxt.coincheck(),ccxt.coinfloor(),ccxt.coingi(),ccxt.coinmarketcap(),ccxt.coinmate(), ccxt.coinsecure(),ccxt.coinspot(),ccxt.cryptopia(),ccxt.dsx(),ccxt.exmo(),ccxt.flowbtc(),ccxt.foxbit(),ccxt.fybse(),ccxt.fybsg(),ccxt.gatecoin(),ccxt.gateio(),ccxt.gdax(), ccxt.gemini(),ccxt.getbtc(),ccxt.hitbtc(),ccxt.huobi(),ccxt.huobicny(),ccxt.independentreserve(),ccxt.itbit(),ccxt.jubi(),ccxt.kraken(),ccxt.kucoin(), ccxt.kuna(),ccxt.lakebtc(),ccxt.liqui(),ccxt.livecoin(),ccxt.luno(),ccxt.mercado(),ccxt.mixcoins(),ccxt.nova(),ccxt.okcoincny(),ccxt.okcoinusd(),ccxt.okex(),ccxt.paymium(), ccxt.poloniex(),ccxt.qryptos(),ccxt.quadrigacx(),ccxt.southxchange(),ccxt.surbitcoin(),ccxt.therock(),ccxt.tidex(),ccxt.urdubit(),ccxt.vaultoro(),ccxt.vbtc(), ccxt.virwox(),ccxt.wex(),ccxt.xbtce(),ccxt.yobit(),ccxt.yunbi(),ccxt.zaif(),ccxt.zb()] for count, exchange in enumerate([str(x) for x in exchanges]): if exchange_in.lower() in exchange: return exchanges[count] break
def cryptopiaData(): cryptopia = ccxt.cryptopia() coindata = list(cryptopia.fetch_tickers().values()) columns = ['ask', 'bid', 'close', 'high', 'low', 'last', 'symbol', 'average', 'baseVolume', 'timestamp'] df = pd.DataFrame(coindata) df = df[columns] df['exchange'] = 'cryptopia' df['createtime'] = starttime df['baseCurrency'] = list(i.split('/')[0] for i in df['symbol']) df['quotCurrency'] = list(i.split('/')[1] for i in df['symbol']) engine = create_engine("mysql+pymysql://quziyou:0739#[email protected]:5389/coinData?charset=utf8") df.to_sql('coindata_tickers', con=engine, if_exists='append', index=False)
def monitor_price(symbol, exchange): if exchange == "binance": market = ccxt.binance({ 'api_key': 'bLt8i8ah7z5OIhPcjW9XNISudKLWcQ4PxdWSLfK57r1Z1iEz8h4I8kwFSMgwLJR3', 'secret': 'mtKjfWoSP88Y8isnYFHvpgm2TLvOXl0lOdOHiSfnvvvc3hfa4nlsBk9HQ5auD4f6' }) if exchange == "cryptopia": market = ccxt.cryptopia({ 'api_key': '4303ea93de0c4c64af6abf2e35e72fd7', 'secret': 'QuWSpBhV+xE352/6mSVImzaV1APCu2fP2LYOyPhBFVk=' }) if exchange == "hitbtc": market = ccxt.hitbtc({ 'api_key': 'd332ac0c7ca9efb4798a389719d64eaf', 'secret': "daa9b1d96b520b39cedbaefb1cbca34a" }) while True: tick = market.fetch_ticker(symbol) print("Time: %s , Symbol: %s, Last Ask: %.8f, Last Bid: %.8f, High: %.8f, Low: %.8f" % (str(tick["datetime"]), symbol, tick['ask'], tick['bid'], tick['high'], tick['low']))
def setapi(connection, curs, exchange): #pull api curs.execute('SELECT * FROM ' + exchange) # exinfo = curs.fetchall() dex = 0 #make a list of accounts for account in exinfo: apikey = str(exinfo[dex][2]) apisec = str(exinfo[dex][3]) #instantiate api worker.append(ccxt.cryptopia({ "apiKey": apikey, "secret": apisec, "enableRateLimit": True, })) global acct_limits.append(float(exinfo[dex][1])) global acct_reserve.append(float(exinfo[dex][0])) dex += 1 return worker
def get_exchange(exchange): config = CONFIG[exchange] if exchange == "gdax": return ccxt.gdax({ "api_key": config['api_key'], "secret": config['secret'], "password": config['password'] }) if exchange == "binance": return ccxt.binance({ "api_key": config['api_key'], "secret": config['secret'] }) if exchange == "hitbtc": return ccxt.hitbtc({ "api_key": config['api_key'], "secret": config['secret'] }) if exchange == "cryptopia": return ccxt.cryptopia({ "api_key": config['api_key'], "secret": config['secret'] })
ccxt.chilebit(), ccxt.cobinhood(), ccxt.coincheck(), ccxt.coinegg(), ccxt.coinex(), ccxt.coinexchange(), ccxt.coinfloor(), ccxt.coingi(), ccxt.coinmarketcap(), ccxt.coinmate(), ccxt.coinnest(), ccxt.coinone(), ccxt.coinsecure(), ccxt.coinspot(), ccxt.coolcoin(), ccxt.cryptopia(), 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(),
# # 16. WEX # (ccxt.wex(), 'https://wex.nz/exchange/{0}_{1}'), # # 21. CEX.IO # (ccxt.cex(), 'https://cex.io/{0}-{1}'), # 22. YoBit (ccxt.yobit(), 'https://yobit.net/en/trade/{0}/{1}'), # # 24. Gatecoin # (ccxt.gatecoin(), 'https://gatecoin.com/marketData'), # 25. Liqui (ccxt.liqui(), 'https://liqui.io/#/exchange/{0}_{1}'), # # 26. OKEx # (ccxt.okex(), 'https://www.okex.com/'), # 43. Tidex (ccxt.tidex(), 'https://tidex.com/exchange/{0}/{1}'), # 52. Cryptopia (ccxt.cryptopia(), 'https://www.cryptopia.co.nz/Exchange/?market={0}_{1}'), ] def main(): now = datetime.now() # Get all markets res = requests.get('https://api.coinmarketcap.com/v1/ticker/') markets = res.json() print('Number of markets={}'.format(len(markets))) # Pop base currency and USDT (Tether) symbols = ['{}/{}'.format(x['symbol'], BASE_CURRENCY) for x in markets if x['symbol'] not in (BASE_CURRENCY, 'USDT')] print(symbols) # TODO: ZRX symbols.append('ZRX/{}'.format(BASE_CURRENCY))
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 exchange = ccxt.cryptopia({'enableRateLimit': True}) symbol = 'ETH/BTC' timeframe = '1h' candles = exchange.fetch_ohlcv(symbol, timeframe) # timeframe duration in seconds duration = exchange.parse_timeframe(timeframe) # timeframe duration in milliseconds duration *= 1000 pprint([[ exchange.iso8601(int(round(candle[0] / duration)) * duration), candle[1], # o candle[2], # h candle[3], # l candle[4], # c candle[5] # v
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")
def main(argv): delay = 1 all_dict = { 'ETH/DOGE': [ 'cryptopia', 'yobit', ], #'ETH/USDT': [ #'cryptopia', #'yobit', #], } #tikers = cpia.fetch_ticker('ETH/DOGE') #pp(tikers) local_data = True if not local_data: cryptopia = ccxt.cryptopia() yobit = ccxt.yobit() oba = cryptopia.fetch_order_book('ETH/DOGE', {'orderCount': 5}) obb = yobit.fetch_order_book('ETH/DOGE', {'limit': 5}) name_a = cryptopia.name name_b = yobit.name pp(oba) pp(obb) else: name_a = "Cryptopia" name_b = "YoBit" oba = g_a obb = g_b print_exchange_info('ETH/DOGE', name_a, oba, name_b, obb) if local_data: return for symbol, v in all_dict.iteritems(): exlst = [] for idx, ex in enumerate(v): exlst.append(eval('ccxt.%s()' % ex)) #print(exlst[idx].name) if not exlst: print('%s can not be exchange in any exchang' % symbol) continue if len(exlst) == 1: print("%s can only be exchange in %s\n" % (symbol, exlst[0].name)) continue # TODO: 需要两两组合来测试 # 暂时只处理首两个交易所的测试 oblst = [] for ex in exlst: if ex.name == 'Cryptopia': oblst.append(ex.fetch_order_book(symbol, {'orderCount': 5})) elif ex.name == 'YoBit': oblst.append(ex.fetch_order_book(symbol, {'limit': 5})) else: oblst.append(ex.fetch_order_book(symbol)) print_exchange_info(symbol, exlst[0].name, oblst[0], exlst[1].name, oblst[1])
pd.options.display.precision = 8 exchange = 'BTC' coin = 'ETN' symbol = '{}/{}'.format(coin, exchange) # book = api.fetch_order_book(symbol, limit=10) # # asks, bids = book['asks'], book['bids'] # df_asks = pd.DataFrame(asks, columns=cols) # df_bids = pd.DataFrame(bids, columns=cols) tm.sleep(.25), trm.clear(), trm.pos(1, 1) api = cryptopia() while True: try: sep = lambda: trm.writeLine(trm.center('-' * 80), trm.dim, trm.cyan) book = api.fetch_order_book(symbol, limit=5) asks, bids = book['asks'], book['bids'] df_asks = pd.DataFrame(asks, columns=cols) df_bids = pd.DataFrame(bids, columns=cols) df_asks['amount'] = df_asks['amount'].apply( lambda v: '{: >16.2f}'.format(v)) df_asks['price'] = df_asks['price'].apply( lambda v: '{: >16.8f}'.format(v)) df_bids['amount'] = df_bids['amount'].apply( lambda v: '{: >16.2f}'.format(v)) df_bids['price'] = df_bids['price'].apply(
import ccxt import logging import pandas as pd EXCHANGES = ['Bittrex', 'Binance', 'Kucoin', 'HuobiPro', 'Cryptopia', 'IDEX'] bittrex_exchange = ccxt.bittrex() binance_exchange = ccxt.binance() kucoin_exchange = ccxt.kucoin() huobiPro_exchange = ccxt.huobipro() cryptopia_exchange = ccxt.cryptopia() bitfinex_exchange = ccxt.bitfinex() list_of_exchanges = { "Bittrex": bittrex_exchange, "Binance": binance_exchange, "Kucoin": kucoin_exchange, "HuobiPro": huobiPro_exchange, "Cryptopia": cryptopia_exchange, "Bitfinex": bitfinex_exchange } ABSOLUTE_PATH = "../data/" def get_coin_exchange_past_trades(csv_filename, exchange): fields = ['coin', 'exchange', 'time'] path = ABSOLUTE_PATH + csv_filename df_csv = pd.read_csv(path, index_col=None, skipinitialspace=True, usecols=fields) df_csv = df_csv.set_index(['coin', 'exchange', 'time']) data = list(df_csv.index.get_level_values(0).unique())
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 exchange = ccxt.cryptopia({'enableRateLimit': True}) symbol = 'ETH/BTC' timeframe = '1h' candles = exchange.fetch_ohlcv(symbol, timeframe) # timeframe duration in seconds duration = exchange.parse_timeframe(timeframe) # timeframe duration in milliseconds duration *= 1000 pprint([ [ exchange.iso8601(int(round(candle[0] / duration)) * duration), candle[1], # o candle[2], # h candle[3], # l
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help='the data.json file') args = parser.parse_args() table = BeautifulTable() table.column_headers = ["pair", "price", "ratio", "size", "note"] table.numeric_precision = 8 exchanges = { "bittrex": ccxt.bittrex(), "poloniex": ccxt.poloniex(), "bitfinex": ccxt.bitfinex(), "cryptopia": ccxt.cryptopia(), "kraken": ccxt.kraken(), "liqui": ccxt.liqui(), "binance": ccxt.binance() } def load_data(filename): with open(args.filename, 'r') as f: data = json.load(f, object_pairs_hook=OrderedDict) return data def translate_dash_to_slash(pair): """ Translates BTC-1ST to 1ST/BTC