Example #1
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 #2
0
def hitbtcData():
    betime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    try:
        hitbtc = ccxt.hitbtc()
        coindata = list(hitbtc.fetch_tickers().values())
        columns = ['symbol', 'ask', 'bid', 'close', 'last', 'high', 'low', 'info', 'datetime']
        df = pd.DataFrame(coindata)
        df = df[columns]
        df['exchange'] = 'hitbtc'
        df['vol'] = [i['volume'] for i in df['info']]
        df['datetime'] = [i.replace('T', ' ') for i in df['datetime']]
        df['datetime'] = [i.replace('Z', '') for i in df['datetime']]
        df = df.drop(['info'], axis=1)
        df['basecurrency'] = list(i.split('/')[0] for i in df['symbol'])
        df['quotcurrency'] = list(i.split('/')[1] for i in df['symbol'])
        df['createtime'] = starttime
        df['codeid'] = 2
        try:
            engine = create_engine("mysql+pymysql://coin:[email protected]:3306/coindata?charset=utf8")
            df.to_sql('coindata_tickers', con=engine, if_exists='append', index=False)
        except:
            with open('coindataerr.log','a') as f:
                f.write('%s:hitbtc数据入库失败!\n' % betime)
                pass
    except:
        with open('coindataerr.log','a') as f:
            f.write('%s:hitbtc数据获取失败!\n' % betime)
        pass
Example #3
0
 def __init__(self,
              deposit_address,
              buy_coin,
              sell_coin,
              exchange: ccxt.hitbtc = None):
     ExchangeAccount.__init__(
         self, deposit_address, buy_coin, sell_coin,
         exchange if exchange is not None else ccxt.hitbtc())
Example #4
0
def test6():
    symbol = 'ETH/BTC'
    t1 = Exchange.Exchange(ccxt.binance())
    t1.add_book(abook, symbol)
    t2 = Exchange.Exchange(ccxt.hitbtc())
    t2.add_book(bbook, 'ETH/BTC')
    pair = Pair.Pair(t1, t2, 'ETH/BTC')
    for i in range(int(10 * pair.min_trade()), int(10 * pair.max_trade())):
        print(pair.roi(i / 10.0))
Example #5
0
def HitBTC():
    symbol = 'COSS/ETH'
    exchange = ccxt.hitbtc()
    markets = exchange.load_markets()
    ticker = exchange.fetch_ticker(symbol.upper())
    print(ticker)
    avgPrice = (ticker['bid'] + ticker['ask']) / 2
    print(avgPrice)
    return avgPrice
Example #6
0
def api_by_name(exchange_name):
    if exchange_name == 'exmo':
        return ccxt.exmo()
    elif exchange_name == 'yobit':
        return ccxt.yobit()
    elif exchange_name == 'hitbtc':
        return ccxt.hitbtc()
    elif exchange_name == 'livecoin':
        return ccxt.livecoin()
    else:
        raise Exception("Unknown exchange")
Example #7
0
    def __init__(self, channels=[]):

        self.channels = channels
        self.check_tradepair()
        # Disabbling logging.
        logger = logging.getLogger()
        logger.disabled = True

        self.hitbtc = ccxt.hitbtc()
        self.hitbtc.load_products()
        self.pub = Publisher(channels)
Example #8
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 #9
0
def hitbtcData():
    hitbtc = ccxt.hitbtc()
    coindata = list(hitbtc.fetch_tickers().values())

    columns = ['ask', 'bid', 'close', 'high', 'low', 'last', 'symbol', 'average', 'baseVolume', 'timestamp']
    df = pd.DataFrame(coindata)
    df = df[columns]
    df['exchange'] = 'hitbtc'
    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)
Example #10
0
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
Example #11
0
def test7():
    symbol = 'ETH/BTC'
    t1 = Exchange.Exchange(ccxt.binance())
    t1.add_book(abook, symbol)
    t2 = Exchange.Exchange(ccxt.hitbtc())
    t2.add_book(abook, 'ETH/BTC')
    pair = Pair.Pair(t1, t2, 'ETH/BTC')
    print(pair.max_trade())
    print(pair.min_trade())
    print(pair.Margin)
    print(pair.margin(pair.max_trade()))
    print(pair.margin(pair.min_trade()))
    print(
        '$', "%.2f" % botutils.convert_to_USD(pair.max_trade(), 'ETH'),
        ' -> $', "%.2f" % botutils.convert_to_USD(
            pair.max_trade() + pair.roi(pair.max_trade()), 'ETH'))
Example #12
0
def test_get_common_symbols():
  print("Testing get_common_symbols()...")
  a = ccxt.exmo()
  b = ccxt.hitbtc()
  c = ccxt.kraken()
  d = ccxt.binance()
  e = ccxt.huobi()
  f = "myMadeUpExchangeName"
  g = "binance"
  s0 = "BTC/USDT"
  s1 = "LTC/BTC"
  s3 = "Not real"
  assert get_common_symbols(a, b) is not None, "Should have some in common"
  assert s0 in get_common_symbols(a, b), s0 + " is in both of these."
  assert get_common_symbols(a, f) is None, "Made up exchange"
  assert len(get_common_symbols(a, b)) == 14, "Should have consistent length."
  print("Passed get_common_symbols() test...")
Example #13
0
def simple_simulate(exchange0=ccxt.exmo(), exchange1=ccxt.hitbtc(),\
    symbol="BTC/USDT", duration=5.0):
    """Run the simple simulation."""
    start_time = time.time()
    rate_limit = max(exchange0.rateLimit, exchange1.rateLimit)
    exchange0.load_markets()
    exchange1.load_markets()
    profits = 0.0
    while (time.time() - start_time) < duration * 60.0:
        cost = get_buy_price(exchange0, exchange1, symbol)
        revenue = get_sell_price(exchange0, exchange1, symbol)
        profits += make_trade(revenue, cost)
        time.sleep(rate_limit / 1000.0)
    print("Total profits made trading on " + exchange0.name + " and "\
        + exchange1.name + " in the market of " + symbol + " over "\
        + str(duration) + " minutes were:")
    print(profits)
    return profits
Example #14
0
 def get(cls):
     return {
         'binance':
         ccxt.binance({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'bitstamp':
         ccxt.bitstamp({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'bittrex':
         ccxt.bittrex({
             'apiKey': os.environ.get("BITTREX_KEY"),
             'secret': os.environ.get("BITTREX_SECRET"),
         }),
         'gdax':
         ccxt.gdax({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'hitbtc':
         ccxt.hitbtc({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'kraken':
         ccxt.kraken({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'liqui':
         ccxt.liqui({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         'poloniex':
         ccxt.poloniex({
             'apiKey': 'YOUR_PUBLIC_API_KEY',
             'secret': 'YOUR_SECRET_PRIVATE_KEY',
         }),
         # add additional supported exchanges
     }
Example #15
0
    def test_smoke_cctx(self):
        print("yup test_cctx")
        hitbtc = ccxt.hitbtc({'verbose': True})
        bitmex = ccxt.bitmex()
        huobi = ccxt.huobi()
        exmo = ccxt.exmo({
            'apiKey': 'YOUR_PUBLIC_API_KEY',
            'secret': 'YOUR_SECRET_PRIVATE_KEY',
        })

        hitbtc_markets = hitbtc.load_markets()

        print(hitbtc.id, hitbtc_markets)
        print(bitmex.id, bitmex.load_markets())
        print(huobi.id, huobi.load_markets())

        print(hitbtc.fetch_order_book(hitbtc.symbols[0]))
        print(bitmex.fetch_ticker('BTC/USD'))
        print(huobi.fetch_trades('LTC/CNY'))
Example #16
0
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']))
Example #17
0
    def test_ccxt(self):
        #print(ccxt.markets)  # print a list of all available market classes
        hitbtc = ccxt.hitbtc({'verbose': True})
        bitmex = ccxt.bitmex()
        huobi = ccxt.huobi()
        bitfinex = ccxt.bitfinex({
            'apiKey': 'YOUR-API-KEY',
            'secret': 'YOUR-API-KEY',
        })
        okcoinusd = ccxt.okcoinusd({
            'apiKey': 'YOUR-API-KEY',
            'secret': 'YOUR-API-KEY',
        })

        trade_amount = 0.1
        market = 'ETH_USD'
        ticker = okcoinusd.fetch_ticker(market)
        print(ticker)
        print('debug %s' % okcoinusd.create_limit_buy_order(
            market, trade_amount, ticker['ask'] + 1))
def hitbtcAgg(symbols):
    result = []
    try:
        hitbtc = ccxt.hitbtc({
            'apiKey': 'apiKey',
            'secret': 'secret',
            'options': {
                'adjustForTimeDifference': True
            }
        })
        totalBalance = hitbtc.fetch_balance()["free"]
        exchangeSymbols = hitbtc.symbols
        checkSymbols = list(np.intersect1d(exchangeSymbols, symbols))
        allData = hitbtc.fetch_tickers(checkSymbols)
        ethPrice = hitbtc.fetch_ticker("ETH/USDT")["last"]
        btcPrice = hitbtc.fetch_ticker("BTC/USDT")["last"]
        for s in checkSymbols:
            try:
                quote = s.split("/")[-1]
                dataSymbols = allData[s]
                coinBalance = totalBalance.get(s.split("/")[0], 0)
                volume = int(float(dataSymbols["baseVolume"]))
                ask = dataSymbols["ask"]
                bid = dataSymbols["bid"]
                last = float(dataSymbols["last"])
                if quote == "BTC":
                    volume = int(volume * btcPrice * last)
                elif quote == "ETH":
                    volume = int(volume * ethPrice * last)
                else:
                    volume = int(volume * dataSymbols["last"])
                volume = volume / ethPrice
                result.append(["hitbtc", s, coinBalance, ask, bid, volume])
            except:
                print("Hitbtc couldn`t get " + s)
                continue
    except Exception as e:
        print(str(e)[:150])
    return (result)
Example #19
0
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']
        })
Example #20
0
def test_get_spread():
  print("Testing get_spread()...")
  a = ccxt.exmo()
  b = ccxt.hitbtc()
  c = ccxt.kraken()
  d = ccxt.binance()
  e = ccxt.huobi()
  f = "myMadeUpExchangeName"
  g = "binance"
  s0 = "BTC/USDT"
  s1 = "LTC/BTC"
  s3 = "Not real"
  assert get_spread(a, b, s0)[0] is not None, "Example of valid comparison"
  assert get_spread(a, b, s1)[0] is not None, "Example of valid comparison"
  assert get_spread(d, c, s0)[0] is None, "Example of market without sym"
  assert get_spread(a, f, s0)[0] is None, "Example of invalid exchange"
  assert get_spread(a, b, s3)[0] is None, "Example of invalid symbol"
  assert get_spread(a, b, s0, True)[0] <= 1, "Percent should be less than 1"
  assert get_spread(a, b, s0, True)[0] >= 0, "Spread cannot be less than 1"
  assert get_spread(a, b, s0)[0] >= 0, "Spread cannot be less than 1"
  assert len(get_spread(a, b, s0)) == 3, "Tuple length should be 3."
  assert len(get_spread(a, f, s0)) == 3, "Tuple length should be 3."
  assert len(get_spread(a, b, s3)) == 3, "Tuple length should be 3."
  print("Passed get_spreads() test...")
Example #21
0
# coindeal = ccxt.coindeal({
#         'enableRateLimit':True,
# })
# # enter your API public/secret keys here:
# coindeal.apiKey = my_API_keys.coindeal.apiKey
# coindeal.secret = my_API_keys.coindeal.secret

gemini = ccxt.gemini({
    'enableRateLimit': True,
})
# enter your API public/secret keys here:
gemini.apiKey = API_keys.gemini.apiKey
gemini.secret = API_keys.gemini.secret

hitbtc = ccxt.hitbtc({
    'enableRateLimit': True,
})
# enter your API public/secret keys here:
hitbtc.apiKey = API_keys.hitbtc.apiKey
hitbtc.secret = API_keys.hitbtc.secret

kraken = ccxt.kraken({
    'enableRateLimit': True,
})
# enter your API public/secret keys here:
kraken.apiKey = API_keys.kraken.apiKey
kraken.secret = API_keys.kraken.secret

liquid = ccxt.liquid({
    'enableRateLimit': True,
})
Example #22
0
def exchange():
    cursor = con.cursor()
    kraken = ccxt.kraken()
    df = kraken.fetchTicker('BTC/USD')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('kraken',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    cursor = con.cursor()
    bitfinex = ccxt.bitfinex()
    df = bitfinex.fetchTicker('BTC/USD')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('bitfinex',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    # cursor = con.cursor()
    # poloniex = ccxt.poloniex()
    # df = poloniex.fetchTicker('BTC/USD')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('poloniex',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    cursor = con.cursor()
    bitmex = ccxt.bitmex()
    df = bitmex.fetchTicker('BTC/USD')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('bitmex',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    cursor = con.cursor()
    bittrex = ccxt.bittrex()
    df = bittrex.fetchTicker('BTC/USDT')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('bittrex',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    cursor = con.cursor()
    hitbtc = ccxt.hitbtc()
    df = hitbtc.fetchTicker('BTC/USDT')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('hitbtc',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    # cursor = con.cursor()
    # okex = ccxt.okex()
    # df = okex.fetchTicker('BTC/USD')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('okex',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    # cursor = con.cursor()
    # deribit = ccxt.deribit()
    # df = deribit.fetchTicker('BTC/USD')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('deribit',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    # cursor = con.cursor()
    # acx = ccxt.acx()
    # df = acx.fetchTicker('BTC/USDT')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('acx',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    cursor = con.cursor()
    bitstamp = ccxt.bitstamp()
    df = bitstamp.fetchTicker('BTC/USD')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('bitstamp',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    # cursor = con.cursor()
    # gemini = ccxt.gemini()
    # df = gemini.fetchTicker('BTC/USD')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('gemini',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    cursor = con.cursor()
    binance = ccxt.binance()
    df = binance.fetchTicker('BTC/USDT')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('binance',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()

    # cursor = con.cursor()
    # qryptos = ccxt.qryptos()
    # df = qryptos.fetchTicker('BTC/USDT')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('qryptos',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    # cursor = con.cursor()
    # huobi = ccxt.huobi()
    # df = huobi.fetchTicker('BTC/USDT')
    # df.pop('info')
    # df1 = [df]

    # cursor.execute("insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('huobi',"+str(df['high'])+","+str(df['low'])+","+str(df['last'])+","+str(df['timestamp'])+","+str(df['bid'])+","+str(df['ask'])+ ")")
    # con.commit()

    cursor = con.cursor()
    cex = ccxt.cex()
    df = cex.fetchTicker('BTC/USD')
    df.pop('info')
    df1 = [df]

    cursor.execute(
        "insert into exchanges(exchangeName,high,low,last,timestamp,bid,ask) values('cex',"
        + str(df['high']) + "," + str(df['low']) + "," + str(df['last']) +
        "," + str(df['timestamp']) + "," + str(df['bid']) + "," +
        str(df['ask']) + ")")
    con.commit()
    return "data inserted"
Example #23
0
        plt.clf()
        profit_cumulative = []
        profit_cumulative.append(self.profit[0])
        for i in range(1, len(self.profit)):
            profit_cumulative.append(self.profit[i]\
                    + profit_cumulative[i - 1])
        plt.plot(range(len(profit_cumulative)), profit_cumulative)
        plt.suptitle("Cumulative Profit over Time")
        plt.ylabel("Cumulative Profit (" + self.quote_currency + ")")
        plt.xlabel("Time (number of trades since start)")
        plt.savefig("crypto/static/graphs/output_profit.png")
        plt.clf()

if __name__ == "__main__":
    CHOICES = [
        ArbitrageSimulation(ccxt.bittrex(), ccxt.hitbtc(), "BTC/USDT"),
        ArbitrageSimulation(ccxt.exmo(), ccxt.gdax(), "BTC/USD"),
        ArbitrageSimulation(ccxt.exmo(), ccxt.kraken(), "BTC/EUR"),
        ArbitrageSimulation(ccxt.bitfinex(), ccxt.exmo(), "ETH/USD"),
    ]
    if len(sys.argv) > 1:  # can provide commandline args to run simulation
        PARSER = argparse.ArgumentParser(description="Produces visual output"\
                + " from simulator with the given parameters.")
        PARSER.add_argument("simulation_type", help="whether to simulate a"\
                + " duration (0) or for to time a profit (1).", type=int,\
                choices=[0, 1])
        PARSER.add_argument("limit_value",\
                help="If duration, the time in minutes if timing a profit,"\
                + " the amount of profit.", type=float)
        PARSER.add_argument("simulation_choice",\
                help="Which default simulation to use.", type=int,\
Example #24
0
 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(),
 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(),
Example #25
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 16:26:15 2018

@author: nathanielastudillo
"""
import ccxt
import time

#Auth
hitbtc = ccxt.hitbtc()
hitbtc.apiKey = ''
hitbtc.secret = ''

profitcount = 0
losscount = 0
'''
!!!Let's also add a way to keep track of all of the trades!!!

For each pair in bottom pairs, indexes are as follows:
    [name, volume, priceWhenPurchased]
    [  0 ,   1   ,     2             ]
'''
amount = 100
counter = 0
bottom10 = []
rounds = 0
cycles = 1

while counter < cycles:
Example #26
0
import json
import time
import unicodecsv as csv
from datetime import datetime

#hitbtc = ccxt.hitbtc({'verbose': True})
#bitmex = ccxt.bitmex()
#binance = ccxt.binance()
exchanges = {
    'coinmarketcap': ccxt.coinmarketcap(),
    'binance': ccxt.binance(),
    'bitmex': ccxt.bitmex(),
    'bitfinex': ccxt.bitfinex(),
    'kraken': ccxt.kraken(),
    'kucoin': ccxt.kucoin(),
    'hitbtc': ccxt.hitbtc({'verbose': True})
}

with open('ccxt_data.csv', 'wb') as outfile:
    fieldnames = ["exchange", "symbol", "data"]
    schreiber = csv.DictWriter(outfile,
                               fieldnames=fieldnames,
                               encoding='utf-8')
    #schreiber.writeheader()

    for name, ex in exchanges.items():
        exchange = ex
        exchange.load_markets()
        if exchange.has['fetchOHLCV']:
            for symbol in exchange.markets:
                time.sleep(exchange.rateLimit /
Example #27
0

# instantiate exchanges

gdax = ccxt.gdax({
    'apiKey': '92560ffae9b8a01d012726c698bcb2f1',  # standard
    'secret':
    '9aHjPmW+EtRRKN/OiZGjXh8OxyThnDL4mMDre4Ghvn8wjMniAr5jdEZJLN/knW6FHeQyiz3dPIL5ytnF0Y6Xwg==',
    'password': '******',  # GDAX requires a password!
})

gdax.urls[
    'api'] = 'https://api-public.sandbox.gdax.com'  # use the testnet for GDAX

hitbtc = ccxt.hitbtc({
    'apiKey': '18339694544745d9357f9e7c0f7c41bb',
    'secret': '8340a60fb4e9fc73a169c26c7a7926f5',
})

quadrigacx = ccxt.quadrigacx({
    'apiKey': 'jKvWkMqrOj',
    'secret': 'f65a2e3bf3c73171ee14e389314b2f78',
    'uid': '395037',  # QuadrigaCX requires uid!
})

try:

    # fetch account balance from the exchange
    gdaxBalance = gdax.fetch_balance()

    # output the result
    dump(green(gdax.name), 'balance', gdaxBalance)
Example #28
0
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.hitbtc({
    'apiKey': "YOUR_API_KEY",
    'secret': "YOUR_SECRET",
    '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:')
Example #29
0
def init_supported_exchanges():
    objects = {
        "acx": ccxt.acx(),
        "aofex": ccxt.aofex(),
        "bequant": ccxt.bequant(),
        "bibox": ccxt.bibox(),
        "bigone": ccxt.bigone(),
        "binance": ccxt.binance(),
        "bitbank": ccxt.bitbank(),
        "bitbay": ccxt.bitbay(),
        "bitfinex": ccxt.bitfinex(),
        "bitflyer": ccxt.bitflyer(),
        "bitforex": ccxt.bitforex(),
        "bithumb": ccxt.bithumb(),
        "bitkk": ccxt.bitkk(),
        "bitmax": ccxt.bitmax(),
        "bitstamp": ccxt.bitstamp(),
        "bittrex": ccxt.bittrex(),
        "bitz": ccxt.bitz(),
        "bl3p": ccxt.bl3p(),
        "bleutrade": ccxt.bleutrade(),
        "braziliex": ccxt.braziliex(),
        "btcalpha": ccxt.btcalpha(),
        "btcbox": ccxt.btcbox(),
        "btcmarkets": ccxt.btcmarkets(),
        "btctradeua": ccxt.btctradeua(),
        "bw": ccxt.bw(),
        "bybit": ccxt.bybit(),
        "bytetrade": ccxt.bytetrade(),
        "cex": ccxt.cex(),
        "chilebit": ccxt.chilebit(),
        "coinbase": ccxt.coinbase(),
        "coinbasepro": ccxt.coinbasepro(),
        "coincheck": ccxt.coincheck(),
        "coinegg": ccxt.coinegg(),
        "coinex": ccxt.coinex(),
        "coinfalcon": ccxt.coinfalcon(),
        "coinfloor": ccxt.coinfloor(),
        "coinmate": ccxt.coinmate(),
        "coinone": ccxt.coinone(),
        "crex24": ccxt.crex24(),
        "currencycom": ccxt.currencycom(),
        "digifinex": ccxt.digifinex(),
        "dsx": ccxt.dsx(),
        "eterbase": ccxt.eterbase(),
        "exmo": ccxt.exmo(),
        "exx": ccxt.exx(),
        "foxbit": ccxt.foxbit(),
        "ftx": ccxt.ftx(),
        "gateio": ccxt.gateio(),
        "gemini": ccxt.gemini(),
        "hbtc": ccxt.hbtc(),
        "hitbtc": ccxt.hitbtc(),
        "hollaex": ccxt.hollaex(),
        "huobipro": ccxt.huobipro(),
        "ice3x": ccxt.ice3x(),
        "independentreserve": ccxt.independentreserve(),
        "indodax": ccxt.indodax(),
        "itbit": ccxt.itbit(),
        "kraken": ccxt.kraken(),
        "kucoin": ccxt.kucoin(),
        "lakebtc": ccxt.lakebtc(),
        "latoken": ccxt.latoken(),
        "lbank": ccxt.lbank(),
        "liquid": ccxt.liquid(),
        "livecoin": ccxt.livecoin(),
        "luno": ccxt.luno(),
        "lykke": ccxt.lykke(),
        "mercado": ccxt.mercado(),
        "oceanex": ccxt.oceanex(),
        "okcoin": ccxt.okcoin(),
        "okex": ccxt.okex(),
        "paymium": ccxt.paymium(),
        "poloniex": ccxt.poloniex(),
        "probit": ccxt.probit(),
        "southxchange": ccxt.southxchange(),
        "stex": ccxt.stex(),
        "surbitcoin": ccxt.surbitcoin(),
        "therock": ccxt.therock(),
        "tidebit": ccxt.tidebit(),
        "tidex": ccxt.tidex(),
        "upbit": ccxt.upbit(),
        "vbtc": ccxt.vbtc(),
        "wavesexchange": ccxt.wavesexchange(),
        "whitebit": ccxt.whitebit(),
        "yobit": ccxt.yobit(),
        "zaif": ccxt.zaif(),
        "zb": ccxt.zb()
    }
    return objects
Example #30
0
'''
Created on 1 Jan 2018

@author: cmt
'''

import ccxt

print 'Start'
print 'Supported exchanges:'
print(ccxt.exchanges)

hitbtc = ccxt.hitbtc({'verbose': False})
hitbtc_markets = hitbtc.load_markets()

print('HITBTC markets:')
print('hitbtc:\n', hitbtc.id, hitbtc_markets)

print('All sympols')
for symbol in hitbtc.symbols:
    print symbol
    
print('Order book for ', hitbtc.symbols[0])
print(hitbtc.fetch_order_book(hitbtc.symbols[0]))

print 'End'

if __name__ == '__main__':
    pass
Example #31
0
# coding=utf-8

import ccxt
import time
hitbtc = ccxt.hitbtc({'verbose': True})
bitmex = ccxt.bitmex()
huobi = ccxt.huobi()
exmo = ccxt.exmo({
    'apiKey': 'YOUR_PUBLIC_API_KEY',
    'secret': 'YOUR_SECRET_PRIVATE_KEY',
})

t1 = time.time()
gateio = ccxt.gateio()
t2 = time.time()
# print gateio.load_markets()
print gateio.fetch_ticker('DAI/USDT')
t3 = time.time()
print t3 - t2, t2 - t1
# print gateio.market_id('DAI/USDT')
# print gateio.fetch_balance()


def test():
    hitbtc_markets = hitbtc.load_markets()
    print(hitbtc.id, hitbtc_markets)
    print(bitmex.id, bitmex.load_markets())

    print(huobi.id, huobi.load_markets())

    print(hitbtc.fetch_order_book(hitbtc.symbols[0]))
Example #32
0
def dump(*args):
    print(' '.join([str(arg) for arg in args]))


# instantiate exchanges

gdax = ccxt.gdax({
    'apiKey': '92560ffae9b8a01d012726c698bcb2f1',  # standard
    'secret': '9aHjPmW+EtRRKN/OiZGjXh8OxyThnDL4mMDre4Ghvn8wjMniAr5jdEZJLN/knW6FHeQyiz3dPIL5ytnF0Y6Xwg==',
    'password': '******',  # GDAX requires a password!
})

gdax.urls['api'] = 'https://api-public.sandbox.gdax.com'  # use the testnet for GDAX

hitbtc = ccxt.hitbtc({
    'apiKey': '18339694544745d9357f9e7c0f7c41bb',
    'secret': '8340a60fb4e9fc73a169c26c7a7926f5',
})

quadrigacx = ccxt.quadrigacx({
    'apiKey': 'jKvWkMqrOj',
    'secret': 'f65a2e3bf3c73171ee14e389314b2f78',
    'uid': '395037',  # QuadrigaCX requires uid!
})

try:
    # fetch account balance from the exchange
    gdaxBalance = gdax.fetch_balance()

    # output the result
    dump(green(gdax.name), 'balance', gdaxBalance)