Example #1
0
 def __init__(self, name):
     self.name = name
     self.conf = Settings.makeSettings(Settings.loadTomlSettings(name))
     secret = open(self.conf.credentialsFilePath).read()
     secret = secret.split('\n')
     self.API = ccxt.binance({
         'apiKey': secret[0],
         'secret': secret[1]
     })
     self.API.load_markets()
Example #2
0
 def set_tickers(self):
     global session_key
     if session_key:
         s = SessionStore(session_key=session_key)
         s.delete()
     exchange = ccxt.binance()
     s = SessionStore()
     s['tickers'] = exchange.fetch_tickers()
     s.create()
     session_key = s.session_key
Example #3
0
 def __init__(self):
     self.exchanges = {
         'binanceus': ccxt.binanceus(),
         'bittrex': ccxt.bittrex(),
         # 'coinbase': ccxt.coinbase(),   # coinbase has most currency pairs, by like 3 times the next highest, consider removing. Also coinbase limits API to 3-6 calls/sec
         'gemini': ccxt.gemini(),
         # 'kraken': ccxt.kraken(),       # updating their API
         'livecoin': ccxt.livecoin(),
         'theocean': ccxt.theocean(),
         # 'okex': ccxt.okex(),            #Canadian, does not allow us
         'bitmart': ccxt.bitmart(),
         # 'cex': ccxt.cex(),  # EU
         # 'bitbay': ccxt.bitbay(),  # EU, Updating API
         # 'bcex': ccxt.bcex(),            #candian exch, their API is updating
         # 'bitbay': ccxt.bitbay(),
         'paymium': ccxt.paymium(),
         'binance': ccxt.binance(),
         'okcoin': ccxt.okcoin(),
         'bitfinex': ccxt.bitfinex()  # non-US
     }
     # creates a markets variable in each exchange instance.  ex. exchages[0].markets will return markets
     self.loadMarkets()
     # these are tickers available on exchnage, but not US customers, or don't allow deposits/withdrawals
     self.unavailableTickers = {
         'binanceus': [],
         'bittrex': [
             'LUNA/BTC', 'ABBC/BTC', 'Capricoin/BTC', 'DRGN/BTC', 'CVT/BTC',
             'NXT/BTC'
         ],
         # 'coinbase': [],
         'gemini': [],
         # 'kraken': [],               # Updating their API
         'livecoin': [
             'BTM/BTC', 'BTM/ETH', 'NANO/BTC', 'NANO/ETH', 'XTZ/BTC',
             'XTZ/ETH', 'THETA/BTC', 'THETA/ETH', 'ABBC/BTC', 'ABBC/ETH',
             'AE/BTC', 'AE/ETH', 'IOST/BTC', 'IOST/ETH'
         ],
         'theocean': [],
         # 'okex': ['AET/ETH','AET/BTC'],             # does not allow US, but allows canadian
         'bitmart': [],
         # 'cex': [],
         # 'bitbay': [],
         # 'bcex': [],             #candian exch, their API is updating
         'bitbay': [],
         'paymium': [],
         'binance': [],
         'okcoin': [],
         'bitfinex': []
     }
     self.commonTickers = self.getCommonTickers()
     # then only call fetch_tickers for common_tickers between exchanges
     self.minProfit = 1  # percent profit
     # in USD NOTE: still need to incorporate this. I think coinmarketcap API has a quick conversion call
     self.minVolume = 200
     self.txfrCosts = []
Example #4
0
    def __init__(self):

        os.chdir(sys.path[0])
        self.symbol = "BUSD/USDT"
        self.bid = None
        self.timeout_var = 10

        if (os.path.exists("config.json") and os.stat("config.json").st_size):
            with open("config.json", "r") as f:
                keys = json.load(f)
            api_key = keys['apikey']
            secret_key = keys['secretkey']
        else:
            api_key = input("Enter API key: ")
            secret_key = input("Enter secret key: ")
            with open("config.json", "w") as f:
                temp = json.dumps({'apikey': api_key, 'secretkey': secret_key})
                f.write(temp)

        self.exchange = ccxt.binance({
            'apiKey': api_key,
            'secret': secret_key,
            'timeout': 30000,
            'enableRateLimit': True,
        })

        print(self.is_open())
        bal = self.get_bal()
        print("USDT", bal[0])
        print("BUSD", bal[1])
        tot = bal[0] + bal[1]
        self.initial_tot_bal = self.total_bank()

        if (os.path.exists("raise_data.json")
                and os.stat("raise_data.json").st_size):
            with open('raise_data.json', 'r') as f:
                try:
                    dat = json.load(f)
                except json.decoder.JSONDecodeError as e:
                    print(e)
                    print(f.read())
                    open('raise_data.json', 'w').close()
                    dat = {
                        "last_balance": None,
                        "total_lost": 0,
                        "trading_volume": 0
                    }

            with open('raise_data.json', 'w') as f:
                f.write(json.dumps(dat))
        else:
            with open('raise_data.json', 'w') as f:
                f.write(json.dumps({'last_balance': tot, 'total_lost': 0}))

        self.is_open(display=True)
Example #5
0
    def run(self, ):

        while 1:
            public_client = cbpro.PublicClient()
            binance = ccxt.binance() 
            ticker = binance.fetch_ticker('BTC/USDT')
            self.lock.acquire()
            self.binance_price[0] = ticker['close']
            self.coinbase_price[0] = public_client.get_product_ticker(product_id='BTC-USD')['price']
            self.lock.release()
            time.sleep(2)
Example #6
0
    def init_binance(self):
        binance = ccxt.binance({
            'apiKey': self.apiKey,
            'secret': self.secret,
            'enableRateLimit': True,
            'options': {
                'defaultType': 'future',  # ←-------------- quotes and 'future'
            },
        })

        return binance
Example #7
0
def get_ticker(update, context):
    time.sleep(1)
    print(type(context.args[0]))
    ticker = binance().fetch_ticker(symbol=context.args[0])
    if ticker['info']: del ticker['info']
    text = ''
    for k,v in ticker.items():
        text += k.capitalize() +': '+str(v)+'\n'
    text += 'ChatId:' + str(update.effective_chat.id)
    print(text)
    context.bot.send_message(chat_id=update.effective_chat.id, text=text)
Example #8
0
    def test_real_api(self):
        import ccxt

        client = ccxt.binance()
        provider = CCXTInstrumentProvider(client=client)

        # Act
        provider.load_all()

        # Assert
        self.assertTrue(provider.count > 0)  # No exceptions raised
Example #9
0
    def get_coin_data(self, bot_id, exchange, pair, api_key, secret_key):
        store = self.store
        store.log.info('Run get_bollinger_info ...')
        if exchange == "binance":
            exchange_obj = ccxt.binance({
                'proxies': {
                    'http': 'http://*****:*****@us-wa.proxymesh.com:31280',
                    'https': 'http://*****:*****@us-wa.proxymesh.com:31280',
                },
                'apiKey': api_key,
                'secret': secret_key,
            })
            cur_data = exchange_obj.fetch_ticker(pair)
            bid_price = float(cur_data['info']['bidPrice'])
            ask_price = float(cur_data['info']['askPrice'])
            cur_timestamp = cur_data['timestamp']
            cur_standard_time = datetime.datetime.fromtimestamp(cur_timestamp/1000)

            total_balance = exchange_obj.fetch_balance()
            base_balance = float(total_balance[pair.split("/")[1]]['total'])
            coin_balance = float(total_balance[pair.split("/")[0]]['total'])
            
            buy_exchange_fee = exchange_obj.calculate_fee(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(pair, 'market', 'sell', 1, bid_price, 'maker')
            sell_fee = round(bid_price * float(sell_exchange_fee['rate']), 8)

            ###### Check order status
            query = "select order_id from trading_history where bot.bot_id=%d and filled=0" % (bot_id,)
            store.set_query(query)
            order_id = store.read()
            if len(order_id) > 0:
                if exchange == "binance":
                    order_info = exchange_obj.fetch_order(id=order_id[0][0], symbol=pair)
                    order_status = order_info['status']
                    if order_status == "closed":
                        query = "update trading_history set filled=1 where order_id=%d" % (order_id[0][0], )
                        store.set_query(query)
                        store.write()
                    elif order_status == "open":
                        store.log.info("There are open order still ...")

            context = {
                'bid_price': bid_price,
                'ask_price': ask_price,
                'timestamp': cur_timestamp,
                'date_time': cur_standard_time,
                'coin_balance': coin_balance,
                'base_balance': base_balance,
                'sell_fee': sell_fee,
                'buy_fee': buy_fee,                
                'order_status': order_status
            }
            return context
Example #10
0
 def Orders_excuted(self,history=1,symbol='BTC/USDT'):
         self.history=history
         self.symbol=symbol
         shift=self.history*60*60*1000
         exchange=ccxt.binance()
         exchange.load_markets()
         #symbol='BTC/USDT'
         if exchange.has['fetchTrades']:
           # for symbol in exchange.markets:  # ensure you have called loadMarkets() or load_markets() method.
             d=pd.DataFrame(exchange.fetch_trades (self.symbol,since=exchange.fetchTime(params = {})-shift))
         self.orders=d
def get_binance_history_data(resolution, ticker):

    binance = ccxt.binance()
    if binance.has['fetchOHLCV']:
        candle_close_prices = [
            x[4] for x in binance.fetch_ohlcv(ticker, resolution)
        ]
        # print(candle_close_prices)
        print("For %s with step = %s we got %s results" %
              (ticker, resolution, len(candle_close_prices)))
        return candle_close_prices
Example #12
0
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
Example #13
0
	def sell_crypto(self, ticker, sell_volume):
		for i in range(10000):
			try:
				sell_trade = self.exchange.create_order(ticker,'market','sell',sell_volume)
				break
			except Exception as e:
				print(e, '\n\nTrying to sell position again')
			self.exchange = ccxt.binance({'apiKey':self.api_keys['api_key'], 'secret':self.api_keys['secret_key']})
		print('\n',sell_trade)

		return sell_trade
	def __init__(self, api_keys, logfile=False, block=False, account_json=None):
		self.api_keys = {'api_key':api_keys['binance_keys']['api_key'],'secret_key':api_keys['binance_keys']['secret_key']}
		self.exchange = ccxt.binance({'apiKey':self.api_keys['api_key'], 'secret':self.api_keys['secret_key']})
		self.logfile = logfile
		self.block = block
		self.started_time = datetime.now()
		self.account_json = account_json

		# Set of tickers to block if specified
		if self.block:
			self.block_set = set()
Example #15
0
def init_supported_exchanges():
    objects = {
        "binance": ccxt.binance(),
        "bitfinex": ccxt.bitfinex(),
        "bitflyer": ccxt.bitflyer(),
        "bitstamp": ccxt.bitstamp(),
        "bittrex": ccxt.bittrex(),
        "coinbase": ccxt.coinbase(),
        "kraken": ccxt.kraken(),
        "poloniex": ccxt.poloniex()
    }
    return objects
Example #16
0
    def __init__(self, trading_pair, timeframe):
        self.exchange = ccxt.binance()
        self.trading_pair = trading_pair
        if timeframe == "5min":
            self.timeframe = "5m"
            self.timeframe_min = 5
        else:
            print("timeframe not implemented")

        self._limit = 1000
        self._second = 1000
        self._minute = 60 * 1000
Example #17
0
 def __init__(self, coin_pair, coin, coin2):
     self.key = get_config()["exchange_key"]
     self.secret = get_config()["exchange_secret"]
     self.exchange = ccxt.binance({
         "apiKey": self.key,
         "secret": self.secret,
         "enableRateLimit": False
     })
     self.coin_pair = coin_pair
     self.coin = coin
     self.coin2 = coin2
     self.paper_enabled = get_config()["paper_trading"]
Example #18
0
	def __init__(self):
		api = pd.read_csv('../api.csv')
		self.binance = ccxt.binance({'options': {'adjustForTimeDifference': True},
					                        'apiKey': api['apiKey'][0],
					                        'secret': api['secret'][0]})

		balance = self.binance.fetchBalance()['free']
		self.coins_units = {coin: units
		   for coin, units
		   in balance.items()
		   if units > 0.01
		   and coin != 'ENJ'}
Example #19
0
 def __init__(self, coin_pair, coin1, coin2):
     self.key = os.getenv("BINANCE_API_KEY")
     self.secret = os.getenv("BINANCE_API_SECRET")
     self.exchange = ccxt.binance({
         "apiKey": self.key,
         "secret": self.secret,
         "enableRateLimit": False
     })
     self.coin_pair = coin_pair
     self.coin = coin1
     self.coin2 = coin2
     self.paper_enabled = "yes"
Example #20
0
def get_binance_connection(key, secret):
    try:
        binance = ccxt.binance({
            'apiKey': key,
            'secret': secret
        })
        log("INFO", "Successfully established connection to Binance API")
        return binance
    except Exception as e:
        log("ERROR", f"Failed to establish connection to Binance API: {e}")

    return
Example #21
0
def create_exchanges():
    """
        instantiate the markets
        to include more exchanges use this function.
        new exchanges need to be hand-coded here
    """
    coinbasepro = ccxt.coinbasepro({
        'apiKey': api_keys.coinbasepro['apiKey'],
        'secret': api_keys.coinbasepro['secret'],
        })

    poloniex = ccxt.poloniex({
        'apiKey': api_keys.poloniex['apiKey'],
        'secret': api_keys.poloniex['secret'],
        })

    bittrex = ccxt.bittrex({
        'apiKey': api_keys.bittrex['apiKey'],
        'secret': api_keys.bittrex['secret'],
        })

    binance = ccxt.binance({
        'apiKey': api_keys.binance['apiKey'],
        'secret': api_keys.binance['secret'],
        })

    bitfinex = ccxt.bitfinex({
        'apiKey': api_keys.bitfinex['apiKey'],
        'secret': api_keys.bitfinex['secret'],
        })

    kraken = ccxt.kraken({
        'apiKey': api_keys.kraken['apiKey'],
        'secret': api_keys.kraken['secret'],
        })

    bitmex = ccxt.bitmex({
        'apiKey': api_keys.bitmex['apiKey'],
        'secret': api_keys.bitmex['secret'],
        })

    okex = ccxt.okex({
        'apiKey': api_keys.okex['apiKey'],
        'secret': api_keys.okex['secret'],
        })

    exchanges = [coinbasepro, poloniex, bittrex, binance, bitfinex, kraken, bitmex, okex]
    timing_limits = [    .35,      .35,       1,     .35,        2,      1,      1,  .35]  # requesting period limit per exchange

    for exchange, timing in zip(exchanges, timing_limits):
        g_storage.timer[exchange.name] = [0, timing]

    return exchanges
Example #22
0
def extract_ohlcv_binance(pair='BTC/USDT', interval='1m', display=False):
    # pair = trading pair (e.g. 'BTC/USDT', 'ETH/USDT', 'BCH/USDT', 'BNB/USDT', 'ADA/USDT')
    # interval = time interval between data points (e.g. '1m', '1h', '1d', '1w', '1M')
    # display = display progress

    # List of ids for all supported exchanges
    # exchange_list = ccxt.exchanges

    # Load exchange and markets
    exchange = ccxt.binance()
    markets = exchange.load_markets()

    # Available trading pairs
    symbols = exchange.symbols
    if not pair in symbols:
        print('Error: Pair not supported.')
        return 0

    # OHLCV (open-highest-lowest-closing-volume) history
    if not exchange.has['fetchOHLCV']:
        print('Error: Cannot fetch OHLCV data.')
        return 0
        
    # Time interval
    tframes = exchange.timeframes
    if not interval in tframes:
        print('Error: Interval not supported')
        return 0
    time_interval = tframes[interval] # Time interval between data points

    # Build dataset
    data = exchange.fetch_ohlcv(pair, interval, since=0) # Initial data
    data_array = np.array(data)

    dataset = np.empty((0,data_array.shape[1])) # Dataset to be built

    # While there is still data to be extracted
    # Note: Can only extract ~1000 data points per fetch_ohlcv call.
    while data:
        if display:
            print(str(len(dataset) + len(data)) + ' data points extracted...')
            
        # Add extracted data to dataset
        dataset = np.vstack([dataset,data_array])
        
        # Timestamp of the last entry
        last_time = int(data_array[-1][0]) 
    
        # Extract next sequence of data
        data = exchange.fetch_ohlcv(pair, interval, since=last_time+1)
        data_array = np.array(data)
        
    return dataset
Example #23
0
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
Example #24
0
    def __init__(self, binance_access_key, binance_secret_key):
        self.binance = ccxt.binance({
            'apiKey': binance_access_key,
            'secret': binance_secret_key,
            'options': {
                'adjustForTimeDifference': True
            },
            'verbose': True
        })

        self.only_btc_tickers, self.only_usdt_tickers, self.both_tickers = self._get_tickers(
        )
Example #25
0
def loadExchanges():
    exchanges = []

    with open(key_file) as json_file:
        keys = json.load(json_file)

    binance = ccxt.binance()
    binance.apiKey = keys['exchanges']['binance']['key']
    binance.secret = keys['exchanges']['binance']['secret']
    exchanges.append(binance)

    return exchanges
Example #26
0
def test4():
    symbol = 'BCD/BTC'
    t1 = Exchange.Exchange(ccxt.binance())
    t1.add_book(abook, symbol)
    t2 = Exchange.Exchange(ccxt.bitz())
    t2.add_book(cbook, 'BCD/BTC')
    pair = Pair.Pair(t1, t2, 'BCD/BTC')
    print(pair.max_trade())
    print(pair.min_trade())
    print(pair.Margin)
    print(pair.FlatFees)
    print(pair.PercentFees)
Example #27
0
def crawl_bybit_datas(symbol, start_time, end_time):
    exchange = ccxt.binance()
    print(exchange)
    current_path = os.getcwd()
    file_dir = os.path.join(current_path, symbol.replace('/', ''))
    print(file_dir)
    if not os.path.exists(file_dir):
        # 如果这个文件路径不存在,则创建这个文件夹,来存放数据.
        os.makedirs(file_dir)

    start_time = start_time
    end_time = end_time
    start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d')
    end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d')
    # 我不知道为什么要*1000
    start_time_stamp = int(time.mktime(start_time.timetuple())) * 1000
    end_time_stamp = int(time.mktime(end_time.timetuple())) * 1000

    limit_count = 200

    while True:
        try:
            print(start_time_stamp)
            data = exchange.fetch_ohlcv(symbol,
                                        timeframe='1d',
                                        since=start_time_stamp,
                                        limit=limit_count)
            df = pd.DataFrame(data)
            df.rename(columns={
                0: 'open_time',
                1: 'open',
                2: 'high',
                3: 'low',
                4: 'close',
                5: 'value'
            },
                      inplace=True)
            # start_time_stamp = int(df.iloc[-1]['open_time'])  # 获取下个请求的时间
            start_time_stamp = int(df.iloc[-1][0])  # 获取下一个次请求的时间.
            filename = str(start_time_stamp) + '.csv'
            save_file_path = os.path.join(file_dir, filename)
            print("文件保存路径为:%s" % save_file_path)
            df.set_index('open_time', drop=True, inplace=True)
            df.to_csv(save_file_path)
            if start_time_stamp > end_time_stamp:
                print("完成请求")
                break
            time.sleep(0.2)

        except Exception as error:
            print(error)
            time.sleep(10)
Example #28
0
def market_depth(sym, exchange=ccxt.binance(), num_entries=20):
    #Get market depth
    #Retrieve and format market depth (order book) including time-stamp
    i = 0  #Used as a counter for number of entries
    print(
        "Order Book: "
    )  #convert_time_binance(client.get_server_time()))   #Transfer to CCXT
    exchange.verbose = True
    depth = exchange.fetch_order_book(symbol=sym)  #Transf'd to CCXT
    #pprint(depth)
    print(depth['asks'][0])
    ask_tot = 0.0
    ask_price = []
    ask_quantity = []
    bid_price = []
    bid_quantity = []
    bid_tot = 0.0
    place_order_ask_price = 0
    place_order_bid_price = 0
    max_order_ask = 0
    max_order_bid = 0
    print("\n", sym, "\nDepth     ASKS:\n")  #Edit to work with CCXT
    print("Price     Amount")
    for ask in depth['asks']:
        if i < num_entries:
            if float(ask[1]) > float(max_order_ask):
                #Determine Price to place ask order based on highest volume
                max_order_ask = ask[1]
                #print("Max Order ASK: ", max_order_ask)
                place_order_ask_price = round(float(ask[0]), 5) - 0.0001
            #ask_list.append([ask[0], ask[1]])
            ask_price.append(float(ask[0]))
            ask_tot += float(ask[1])
            ask_quantity.append(ask_tot)
            #print(ask)
            i += 1
    j = 0  #Secondary Counter for Bids
    print("\n", sym, "\nDepth     BIDS:\n")
    print("Price     Amount")
    for bid in depth['bids']:
        if j < num_entries:
            if float(bid[1]) > float(max_order_bid):
                #Determine Price to place ask order based on highest volume
                max_order_bid = bid[1]
                #print("Max Order BID: ", max_order_bid)
                place_order_bid_price = round(float(bid[0]), 5) + 0.0001
            bid_price.append(float(bid[0]))
            bid_tot += float(bid[1])
            bid_quantity.append(bid_tot)
            #print(bid)
            j += 1
    return ask_price, ask_quantity, bid_price, bid_quantity, place_order_ask_price, place_order_bid_price
Example #29
0
def kimp():
    c = CurrencyConverter('http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip')
    exchange_rate = round(c.convert(1, 'USD', 'KRW'),2) #환율
    #print(exchange_rate)

    binance = ccxt.binance()
    markets_binance = binance.fetch_tickers()
    #print(markets_binance.keys())
    binance_BTC = binance.fetch_ticker('BTC/USDT')
    binance_BTC_close = binance_BTC['close']
    #print(binance_BTC_close)

    upbit = ccxt.upbit()
    markets_upbit = upbit.fetch_tickers()
    #print(markets_upbit.keys())
    upbit_BTC = upbit.fetch_ticker('BTC/KRW')
    upbit_BTC_close = upbit_BTC['close']
    #print(upbit_BTC_close)
    kimp_BTC = round(((upbit_BTC_close/(binance_BTC_close*exchange_rate) - 1) * 100),2)

    binance_ETH = binance.fetch_ticker('ETH/USDT')
    binance_XRP = binance.fetch_ticker('XRP/USDT')
    binance_ADA = binance.fetch_ticker('ADA/USDT')
    binance_ETH_close = binance_ETH['close']
    binance_XRP_close = binance_XRP['close']
    binance_ADA_close = binance_ADA['close']

    upbit_ETH = upbit.fetch_ticker('ETH/KRW')
    upbit_XRP = upbit.fetch_ticker('XRP/KRW')
    upbit_ADA = upbit.fetch_ticker('ADA/KRW')
    upbit_ETH_close = upbit_ETH['close']
    upbit_XRP_close = upbit_XRP['close']
    upbit_ADA_close = upbit_ADA['close']

    kimp_ETH = round(((upbit_ETH_close / (binance_ETH_close * exchange_rate) - 1) * 100))
    kimp_XRP = round(((upbit_XRP_close / (binance_XRP_close * exchange_rate) - 1) * 100))
    kimp_ADA = round(((upbit_ADA_close / (binance_ADA_close * exchange_rate) - 1) * 100))

    format_upbit_BTC_close = format(upbit_BTC_close, ",")[:-2]
    format_upbit_ETH_close = format(upbit_ETH_close, ",")[:-2]
    format_upbit_XRP_close = format(upbit_XRP_close, ",")[:-2]
    format_upbit_ADA_close = format(upbit_ADA_close, ",")[:-2]

    # now = datetime.datetime.now().time()
    now = time.strftime('%y-%m-%d %H:%M:%S')

    s = f"현재시간 : {now} <br><br>\n" \
        f"BTC : {format_upbit_BTC_close} ({kimp_BTC}%) <p> \n" \
        f"ETH : {format_upbit_ETH_close} ({kimp_ETH}%) <p> \n" \
        f"XRP : {format_upbit_XRP_close} ({kimp_XRP}%) <p> \n" \
        f"ADA : {format_upbit_ADA_close} ({kimp_ADA}%)"
    return s
Example #30
0
def request_instruments():
    client = ccxt.binance({
        "apiKey": "",
        "secret": "",
        "timeout": 10000,  # Hard coded for now
        "enableRateLimit": True,  # Hard coded for now
    })

    client.load_markets()
    res = client.markets

    with open('res_instruments.json', 'w') as json_file:
        json.dump(res, json_file)
Example #31
0
    def __init__(self, config, debug=True):
        key_config = config['apikey']
        self.debug = debug
        self.exchanges = {
            'zb': Zb(key_config['zb']['key'], key_config['zb']['secret']),
            'okex': Okex(key_config['okex']['key'], key_config['okex']['secret']),
            'weex': Weex(key_config['weex']['key'], key_config['weex']['secret']),
            # 'huobipro': Huobipro(key_config['huobipro']['key'], key_config['huobipro']['secret']),
            'bithumb': ccxt.bithumb(),
            'binance': ccxt.binance(),
            'bitflyer': ccxt.bitflyer(),
            'hitbtc': ccxt.hitbtc(),
            'coincheck': ccxt.coincheck(),
            "quoinex": ccxt.quoinex(),
            "bitfinex": ccxt.bitfinex(),
            "hitbtc": ccxt.hitbtc(),
        }

        self.engine = MysqlEngine(config['db']['url'])
        self.pool = ThreadPoolExecutor(3)  # for many urls, this should probably be capped at some value.

        self.async = False
Example #32
0
# -*- coding: utf-8 -*-

import os
import sys

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.binance({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
    'enableRateLimit': True,
})

symbol = 'ETH/BTC'
type = 'limit'  # or 'market'
side = 'sell'  # or 'buy'
amount = 1.0
price = 0.060154  # or None

# extra params and overrides if needed
params = {
    'test': True,  # test if it's valid, but don't actually place it
}

order = exchange.create_order(symbol, type, side, amount, price, params)

print(order)
def get_binance_data(symbol, timeframe, length, include_current_candle = True, file_format = ['txt', 'csv'], api_cooldown_seconds = 0):

    """
    Download Crypto OHLCV Data from Binance.

    The function fetches OHLCV data via the specified paramteres from the public Binance API,
    merges it into a Pandas Data Frame and optionally saves the Data Frame as .txt and/or .csv file.
    Through concatenation more data than specified by the maximal request length of the exchange
    can be fetched.
    Additional timeframes are available (merged from smaller timeframes).

    Parameters
    ----------
    symbol : str
        Symbol of the underlying data, e.g. 'BTC/USDT'

    timeframe : str
        Timeframe of the underlying data, e.g. '1h'

    length : int
        Number of Timeframes (Data length), e.g. 500

    include_current_candle : bool
        Include the current, not finished, candle, e.g. True

    file_format : str, list
        Which file format should be used to save the data, e.g. 'csv' or ['txt', 'csv']

    api_cooldown_seconds : int, float
        When fetching a lot of data this allows each request to the API to be made after
        the amount in seconds has passed.
        This prevents possible API errors due to too many requests within a short time.

    Returns
    -------
    Pandas Data Frame and optionally .txt and/or .csv file.
        A table with headers 'Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume' containing the requested data.

    Dependencies
    ------------
    import ccxt
    import time
    import csv
    import pandas as pd

    """

    data_limit = 500 # int(ccxt.binance({}).describe()['ratelimit']) returns 500

    binance_symbols = [market['symbol'] for market in ccxt.binance({}).fetch_markets()]
    binance_timeframes = {'1m': 60*1000, '3m': 3*60*1000, '5m': 5*60*1000, '15m': 15*60*1000, '30m': 30*60*1000, '1h': 60*60*1000, '2h': 2*60*60*1000, '4h': 4*60*60*1000, '6h': 6*60*60*1000, '12h': 12*60*60*1000, '1d': 24*60*60*1000, '3d': 3*24*60*60*1000, '1w': 7*24*60*60*1000}
    missing_timeframes = {'3h': ['1h', 3, 60*60*1000], '2w': ['1w', 2, 7*24*60*60*1000]}

    timestamp = []
    openx = []
    high = []
    low = []
    close = []
    volume = []

    timestamp_temp = []
    openx_temp = []
    high_temp = []
    low_temp = []
    close_temp = []
    volume_temp = []
    
    proceed = True

    if symbol not in binance_symbols:
        print("ERROR:\tPlease use one of the following Symbols:\n\t" + "\n\t".join(sorted(binance_symbols)))
        proceed = False

    if not(timeframe in binance_timeframes.keys() or timeframe in missing_timeframes.keys()):
        print("ERROR:\tPlease use one of the following Timeframes:\n\tMinute:\t'1m', '3m', '5m', '15m', '30m',\n\tHour:\t'1h', '2h', '3h', '4h', '6h', '12h',\n\tDay:\t'1d', '3d',\n\tWeek:\t'1w', '2w'")
        proceed = False
        
    if not isinstance(length, int) or length < 1:
        print("ERROR:\tPlease use a reasonable number for the argument 'length'.")
        proceed = False

    if type(include_current_candle) != bool:
        print("ERROR:\tPlease use boolean values for argument 'include_current_candle' only.")
        proceed = False

    if not(file_format == 'txt' or file_format == 'csv' or file_format == ['txt'] or file_format == ['csv'] or file_format == ['csv', 'txt'] or file_format == ['txt', 'csv'] or
            file_format == '' or file_format == [] or file_format == [''] or file_format == None):
        print("ERROR:\tAllowed values for argument 'file_format' are 'csv', 'txt', ['csv', 'txt'].\n\tIf you do not wish to save the data please use either '', [''], [], None.")
        proceed = False
        
    if file_format == '' or file_format == [] or file_format == [''] or file_format == None:
        file_format = []

    if file_format == 'csv':
        file_format = ['csv']
    if file_format == 'txt':
        file_format = ['txt']

    if not isinstance(api_cooldown_seconds, (int, float)) or api_cooldown_seconds < 0 or api_cooldown_seconds > 60:
        print("ERROR:\tPlease use a reasonable 'api_cooldown_seconds' number of seconds (between 0 and 60).")
        proceed = False

    if proceed == True:
        if timeframe in missing_timeframes.keys():
            if include_current_candle == True:
                n_bulk = (length * missing_timeframes[timeframe][1]) // data_limit
                remainder = (length * missing_timeframes[timeframe][1]) % data_limit
            if include_current_candle == False:
                n_bulk = ((length + 1) * missing_timeframes[timeframe][1]) // data_limit
                remainder = ((length + 1) * missing_timeframes[timeframe][1]) % data_limit

            while n_bulk > 0:
                since = round(ccxt.binance({}).milliseconds() - (ccxt.binance({}).milliseconds() % (missing_timeframes[timeframe][1] * missing_timeframes[timeframe][2])) - (n_bulk * data_limit * missing_timeframes[timeframe][2]) - (remainder * missing_timeframes[timeframe][2]))
                for block in ccxt.binance({}).fetch_ohlcv(symbol = symbol, timeframe = missing_timeframes[timeframe][0], since = (since + (missing_timeframes[timeframe][1] * missing_timeframes[timeframe][2])), limit = data_limit):
                    timestamp_temp.append(block[0])
                    openx_temp.append(block[1])
                    high_temp.append(block[2])
                    low_temp.append(block[3])
                    close_temp.append(block[4])
                    volume_temp.append(block[5])
                n_bulk -= 1
                if n_bulk > 0 or remainder > 0:
                    time.sleep(api_cooldown_seconds)

            if remainder > 0:
                since = round(ccxt.binance({}).milliseconds() - (ccxt.binance({}).milliseconds() % (missing_timeframes[timeframe][1] * missing_timeframes[timeframe][2])) - (remainder * missing_timeframes[timeframe][2]))
                for block in ccxt.binance({}).fetch_ohlcv(symbol = symbol, timeframe = missing_timeframes[timeframe][0], since = (since + (missing_timeframes[timeframe][1] * missing_timeframes[timeframe][2])), limit = remainder + 1):
                    timestamp_temp.append(block[0])
                    openx_temp.append(block[1])
                    high_temp.append(block[2])
                    low_temp.append(block[3])
                    close_temp.append(block[4])
                    volume_temp.append(block[5])

            if length > 1:
                for i in [num for num in range(0, len(timestamp_temp), missing_timeframes[timeframe][1])][:-1]:
                    timestamp.append(timestamp_temp[i])
                    openx.append(openx_temp[i])
                    high.append(max(high_temp[i:i + missing_timeframes[timeframe][1]]))
                    low.append(min(low_temp[i:i + missing_timeframes[timeframe][1]]))
                    close.append(close_temp[i + (missing_timeframes[timeframe][1] - 1)])
                    volume.append(sum(volume_temp[i:i + missing_timeframes[timeframe][1]]))

                # append all available remaining smaller timeframes to the lists
                timestamp.append(timestamp_temp[i + missing_timeframes[timeframe][1]])
                openx.append(openx_temp[i + missing_timeframes[timeframe][1]])
                high.append(max(high_temp[i + missing_timeframes[timeframe][1]:]))
                low.append(min(low_temp[i + missing_timeframes[timeframe][1]:]))
                close.append(close_temp[-1])
                volume.append(sum(volume_temp[i + missing_timeframes[timeframe][1]:]))

            if length == 1:
                timestamp.append(timestamp_temp[0])
                openx.append(openx_temp[0])
                high.append(max(high_temp[0:]))
                low.append(min(low_temp[0:]))
                close.append(close_temp[-1])
                volume.append(sum(volume_temp[0:]))

        if timeframe not in missing_timeframes.keys():
            if include_current_candle == True:
                n_bulk = length // data_limit
                remainder = length % data_limit
            if include_current_candle == False:
                n_bulk = (length + 1) // data_limit
                remainder = (length + 1) % data_limit

            while n_bulk > 0:
                since = ccxt.binance({}).milliseconds() - (n_bulk * data_limit * binance_timeframes[timeframe]) - (remainder * binance_timeframes[timeframe])
                for block in ccxt.binance({}).fetch_ohlcv(symbol = symbol, timeframe = timeframe, since = since, limit = data_limit):
                    timestamp.append(block[0])
                    openx.append(block[1])
                    high.append(block[2])
                    low.append(block[3])
                    close.append(block[4])
                    volume.append(block[5])
                n_bulk -= 1
                if n_bulk > 0 or remainder > 0:
                    time.sleep(api_cooldown_seconds)

            if remainder > 0:
                since = ccxt.binance({}).milliseconds() - (remainder * binance_timeframes[timeframe])
                for block in ccxt.binance({}).fetch_ohlcv(symbol = symbol, timeframe = timeframe, since = since, limit = remainder):
                    timestamp.append(block[0])
                    openx.append(block[1])
                    high.append(block[2])
                    low.append(block[3])
                    close.append(block[4])
                    volume.append(block[5])

        data_identifier = 'binance_' + ''.join(symbol.split('/')) + '_' + str(timeframe) + '_' + str(length) + ('_including_current_candle' if include_current_candle == True else '_NOT_including_current_candle')

        if file_format != []:
            for ending in file_format:
                # specify where to save the files e.g.
                #with open('/Users/username/Desktop/' + data_identifier + '.' + str(ending), 'w') as csvfile:
                with open(data_identifier + '.' + str(ending), 'w') as csvfile:
                    writer = csv.writer(csvfile, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
                    writer.writerow([head for head in ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']])
                    if include_current_candle == True:
                        write = zip(timestamp, openx, high, low, close, volume)
                    if include_current_candle == False:
                        write = zip(timestamp[:-1], openx[:-1], high[:-1], low[:-1], close[:-1], volume[:-1])
                    for entry in write:
                        writer.writerow(entry)

        if include_current_candle == True:
            df = pd.DataFrame(list(zip(timestamp, openx, high, low, close, volume)), columns = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
            df.name = data_identifier
            return df
        if include_current_candle == False:
            df = pd.DataFrame(list(zip(timestamp[:-1], openx[:-1], high[:-1], low[:-1], close[:-1], volume[:-1])), columns = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
            df.name = data_identifier
            return df