Beispiel #1
0
def getMarketPrice(EXCHANGE, SYMBOL):
    if EXCHANGE == "poloniex":
        exchange = ccxt.poloniex()
    elif EXCHANGE == "bittrex":
        exchange = ccxt.bittrex()
    elif EXCHANGE == "kraken":
        exchange = ccxt.kraken()
    markets = exchange.load_markets()
    book = ccxt.poloniex().fetch_order_book(SYMBOL, {'depth': 10})
    # print(book)
    bid = book['bids'][0][0] if len(book['bids']) > 0 else None
    ask = book['asks'][0][0] if len(book['asks']) > 0 else None
    spread = (ask - bid) if (bid and ask) else None
    print({'bid': bid, 'ask': ask, 'spread': spread}, exchange.id, 'market price')
    return spread
Beispiel #2
0
def polo():

    polo_blacklist = get_config('polo', 'blacklist')

    """Handle pulling market data from Poloneix."""
    tickers = ccxt.poloniex().load_markets()
    for pair, result in tickers.items():
        from_currency = pair.split('/')[0]
        to_currency = pair.split('/')[1]

        if from_currency in polo_blacklist:
            return
        if to_currency in polo_blacklist:
            return

        from_amount = 1
        try:
            to_amount = (float(result['info']['highestBid']) + float(result['info']['lowestAsk'])) / 2
            ConversionRate.objects.create(
                from_amount=from_amount,
                to_amount=to_amount,
                source='poloniex',
                from_currency=from_currency,
                to_currency=to_currency)
            print(f'Poloniex: {from_currency}=>{to_currency}:{to_amount}')
        except Exception as e:
            print(e)
def polo():
    """Handle pulling market data from Poloneix."""
    tickers = ccxt.poloniex().load_markets()
    for pair, result in tickers.items():
        from_currency = pair.split('/')[0]
        to_currency = pair.split('/')[1]

        from_amount = 1
        try:
            to_amount = (float(result['info']['highestBid']) +
                         float(result['info']['lowestAsk'])) / 2
            ConversionRate.objects.create(from_amount=from_amount,
                                          to_amount=to_amount,
                                          source='poloniex',
                                          from_currency=from_currency,
                                          to_currency=to_currency)
            print('Poloniex: {}=>{}:{}'.format(from_currency, to_currency,
                                               to_amount))
        except Exception as e:
            print(e)

    for b in Bounty.objects.all():
        print('refreshed {}'.format(b.pk))
        try:
            b._val_usd_db = b.value_in_usdt
            b.save()
        except Exception as e:
            print(e)
            b._val_usd_db = 0
            b.save()
Beispiel #4
0
 def __init__(self):
     """"""
     self.exchange = ccxt.poloniex()
     self.exchange.load_markets()
     self.delay_seconds = self.exchange.rateLimit / 1000
     self.symbols = self.exchange.markets
     self.db_url = 'sqlite:///databases/market_prices.db'
     self.deques = dict()
     self.ohlcv = dict()
     self.database = dataset.connect(self.db_url)
     for symbol in self.symbols:
         if self.exchange.has['fetchOHLCV']:
             print('Obtaining OHLCV data')
             data = self.exchange.fetch_ohlcv(symbol, '1d')
             data = list(zip(*data))
             data[0] = [
                 datetime.datetime.fromtimestamp(ms / 1000)
                 for ms in data[0]
             ]
             self.ohlcv[symbol] = data
             time.sleep(self.delay_seconds)
         else:
             print('No OHLCV data available')
         self.deques[symbol] = deque()
         if len(self.database[symbol]):
             for e in self.database[symbol]:
                 entry = (e['bid'], e['ask'], e['spread'], e['time'])
                 self.deques[symbol].append(entry)
     del self.database
     self.thread = threading.Thread(target=self.__update)
     self.thread.daemon = True
     self.thread.start()
Beispiel #5
0
def poloniexData():
    betime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    try:
        poloniex = ccxt.poloniex()
        coindata = list(poloniex.fetch_tickers().values())
        columns = ['symbol', 'ask', 'bid', 'close', 'last', 'high', 'low', 'info', 'datetime']
        df = pd.DataFrame(coindata)
        df = df[columns]
        df['exchange'] = 'poloniex'
        df['vol'] = [i['baseVolume'] 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:poloniex数据入库失败!\n' % betime)
                pass
    except:
        with open('coindataerr.log','a') as f:
            f.write('%s:poloniex数据获取失败!\n' % betime)
        pass
Beispiel #6
0
    def CreateExchanges(self):
        # Création des exchanges
        exchanges = []

        # Add the desired exchanges here, for instance kraken and poloniex:

        kraken = ccxt.kraken({
            #'apiKey' : 'your key here',
            #'secret':'your secret here'
        })
        exchanges.append(kraken)

        poloniex = ccxt.poloniex({
            #'apiKey' : 'your key here',
            #'secret':'your secret here'
        })
        exchanges.append(poloniex)

        self.loadMarkets(exchanges)

        # Assign default precision to avoid error on gdax
        for exchange in exchanges:
            for symbol in exchange.symbols:
                if 'amount' not in exchange.markets[symbol]['precision']:
                    exchange.markets[symbol]['precision']['amount'] = 8

        return exchanges
Beispiel #7
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]

    # exchanges.pop(exchanges.index(kraken))

    return exchanges
 def __init__(self, channels=[]):
     # Disabbling logging.
     self.channels = channels
     self.check_tradepair()
     logger = logging.getLogger()
     logger.disabled = True
     self.poloniex = ccxt.poloniex()
     self.poloniex.load_products()
     self.pub = Publisher(channels)
Beispiel #9
0
    def handle(self, *args, **options):

        r = requests.get('https://api.etherdelta.com/returnTicker')
        tickers = r.json()

        #etherdelta
        for pair, result in tickers.items():
            from_currency = pair.split('_')[0]
            to_currency = pair.split('_')[1]

            from_amount = 1
            to_amount = (result['bid'] + result['ask']) / 2
            try:
                ConversionRate.objects.create(
                    from_amount=from_amount,
                    to_amount=to_amount,
                    source='etherdelta',
                    from_currency=from_currency,
                    to_currency=to_currency,
                )
                print('{}=>{}:{}'.format(from_currency, to_currency,
                                         to_amount))
            except Exception as e:
                print(e)

        tickers = ccxt.poloniex().load_markets()
        for pair, result in tickers.items():
            from_currency = pair.split('/')[0]
            to_currency = pair.split('/')[1]

            from_amount = 1
            try:
                to_amount = (float(result['info']['highestBid']) +
                             float(result['info']['lowestAsk'])) / 2
                ConversionRate.objects.create(
                    from_amount=from_amount,
                    to_amount=to_amount,
                    source='poloniex',
                    from_currency=from_currency,
                    to_currency=to_currency,
                )
                print('{}=>{}:{}'.format(from_currency, to_currency,
                                         to_amount))
            except Exception as e:
                print(e)

        for b in Bounty.objects.all():
            print('refreshed {}'.format(b.pk))
            try:
                b._val_usd_db = b.value_in_usdt
                b.save()
            except Exception as e:
                print(e)
                b._val_usd_db = 0
                b.save()
Beispiel #10
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
Beispiel #11
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
Beispiel #12
0
 def __init__(self, app):
     self.app = app
     self.webhook = "YOUR SLACK WEBHOOK"
     self.coinmarketcap = Pymarketcap()
     self.bittrex = ccxt.bittrex()
     self.poloniex = ccxt.poloniex()
     self.quadraigacx = ccxt.poloniex()
     self.exchanges = {
         'bittrex': self.bittrex,
         'poloniex': self.poloniex,
         'quadraigacx': self.quadraigacx,
         'coinmarketcap': self.coinmarketcap
     }
     self.loadMarkets()
     self.dispatch_map = {
         'showalert': self.showAlert,
         'removealert': self.removeAlert,
         'alert': self.createAlert,
         'topten': self.topten,
         'updatecoin': self.updatecoin,
         'gainers': self.gainers,
         'losers': self.losers,
         'symbols': self.symbols
     }
     alertFile = Path("alert.p")
     if alertFile.is_file():
         self.alerts = pickle.load(open('alert.p', "rb"))
     else:
         self.alerts = []
     self.symbols = []
     self.timeframe = ['7d', '24h', '1h']
     self.symbols = self.coinmarketcap.symbols
     self.coinmarket_latestinfo = []
     self.bittrex_latestinfo = []
     self.poloniex_latestinfo = []
     self.quadraigacx_latestinfo = []
     scheduler = BackgroundScheduler()
     scheduler.add_job(self.refreshinfo, 'interval', seconds=20)
     logging.basicConfig()
     scheduler.start()
Beispiel #13
0
def get_symbols(exchange="polo"):
    if exchange == "polo":
        polo = ccxt.poloniex()
        polo.load_markets()
        return polo.symbols
    elif exchange == "stock":
        url = "https://www.quandl.com/api/v3/databases/WIKI/codes.json?api_key=%s" % QUANDL_APIKEY
        res = urlopen(url)
        zipfile = ZipFile(BytesIO(res.read()))
        zipfile.extract(zipfile.namelist()[0])
        df = pd.read_csv(zipfile.namelist()[0], header=None)
        return df[0].values
    else:
        raise NotImplementedError()
Beispiel #14
0
def poloniexData():
    poloniex = ccxt.poloniex()
    coindata = list(poloniex.fetch_tickers().values())

    columns = ['ask', 'bid', 'close', 'high', 'low', 'last', 'symbol', 'average', 'baseVolume', 'timestamp']
    df = pd.DataFrame(coindata)
    df = df[columns]
    df['exchange'] = 'poloniex'
    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)
Beispiel #15
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
def live_ticker(tradepair):
    global listOfTradingPairs
    print("Ticker of Currency Pair", tradepair)
    if tradepair in listOfTradingPairs.keys():
        poloniex = ccxt.poloniex()
        poloniex.load_products()
        tradepair = listOfTradingPairs.get(tradepair)
        temp = poloniex.fetch_ticker(tradepair)
        while True:
            if (poloniex.fetch_ticker(tradepair) == temp):
                pass
            else:
                temp = poloniex.fetch_ticker(tradepair)
                print(temp)
    else:
        print("Currency Pair is not from the below list \n",
              listOfTradingPairs.keys())
Beispiel #17
0
 def setup_clients(self):
     self.exchanges['Bittrex'] = ccxt.bittrex({
         'apiKey':
         self.meta['Bittrex']['public'],
         'secret':
         self.meta['Bittrex']['secret'],
     })
     self.exchanges['Poloniex'] = ccxt.poloniex({
         'apiKey':
         self.meta['Poloniex']['public'],
         'secret':
         self.meta['Poloniex']['secret'],
     })
     self.exchanges['YoBit'] = ccxt.yobit({
         'apiKey':
         self.meta['YoBit']['public'],
         'secret':
         self.meta['YoBit']['secret'],
     })
     self.exchanges['HitBTC'] = ccxt.hitbtc2({
         'apiKey':
         self.meta['HitBTC']['public'],
         'secret':
         self.meta['HitBTC']['secret'],
     })
     self.exchanges['Tidex'] = ccxt.tidex({
         'apiKey':
         self.meta['Tidex']['public'],
         'secret':
         self.meta['Tidex']['secret'],
     })
     self.exchanges['Binance'] = ccxt.binance({
         'options': {
             'adjustForTimeDifference': True
         },
         'apiKey':
         self.meta['Binance']['public'],
         'secret':
         self.meta['Binance']['secret'],
     })
     self.exchanges['Bitfinex'] = ccxt.bitfinex({
         'apiKey':
         self.meta['Bitfinex']['public'],
         'secret':
         self.meta['Bitfinex']['secret'],
     })
Beispiel #18
0
 def __init__(self):
     self.k = ct.kraken()
     self.y = ct.yobit()
     self.p = ct.poloniex()
     self.coinmarket = ct.coinmarketcap()
     self.liqui = ct.bitfinex()
     print(ct.exchanges)
     print(self.k.hasFetchOHLCV, self.k.rateLimit)
     print(self.y.hasFetchOHLCV, self.y.rateLimit)
     print(self.p.hasFetchOHLCV, self.p.rateLimit)
     # print(self.coinmarket.hasFetchOHLCV, self.coinmarket.rateLimit)
     keys_conf = conf.TradeKeys()
     #print(keys_conf.keys_info)
     self.k.apiKey = keys_conf.keys_info['kraken']['public']
     self.k.secret = keys_conf.keys_info['kraken']['secret']
     #self.k.load_markets()
     print(self.k.symbols)
Beispiel #19
0
def get_exchange_symbols():

    assets = Assets()
    slugs = get_coincap_slugs()
    exchanges = ['binance', 'bitfinex', 'bittrex', 'poloniex', 'kraken']

    coins = {}

    # loop through exchanges, grab symbols
    for exchange_str in exchanges:
        if exchange_str == 'binance':
            exchange = ccxt.binance()
        elif exchange_str == 'bitfinex':
            exchange = ccxt.bitfinex()
        elif exchange_str == 'bittrex':
            exchange = ccxt.bittrex()
        elif exchange_str == 'poloniex':
            exchange = ccxt.poloniex()
        elif exchange_str == 'kraken':
            exchange = ccxt.kraken()
        else:
            exchange = None

        if exchange:
            exchange.load_markets()
            for sym in exchange.symbols:
                if '/BTC' in sym:
                    sym = sym.replace('/BTC', '')
                    if sym not in coins:
                        coins[sym] = {'exchanges': [exchange_str]}
                    else:
                        coins[sym]['exchanges'].append(exchange_str)

    # handle felix and coincap assets
    for coin in coins:
        if coin in assets:
            coins[coin]['exchanges'].append('felix')
        if coin in slugs:
            coins[coin]['id'] = slugs[coin]['id']
            coins[coin]['name'] = slugs[coin]['name']
        else:
            coins[coin]['id'] = None
            coins[coin]['name'] = None

    sorted_coins = collections.OrderedDict(sorted(coins.items()))
    return sorted_coins
Beispiel #20
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
     }
def poloniexAgg(symbols):
    result = []
    try:
        poloniex = ccxt.poloniex({
            'apiKey': 'apiKey',
            'secret': 'secret',
            'options': {
                'adjustForTimeDifference': True
            }
        })
        allData = poloniex.load_markets()
        totalBalance = poloniex.fetch_balance()["free"]
        ethPrice = allData["ETH/USDT"]["info"]["last"]
        btcPrice = allData["BTC/USDT"]["info"]["last"]
        checkSymbols = poloniex.symbols
        for s in symbols:
            if s in checkSymbols:
                try:
                    quote = s.split("/")[-1]
                    #dataSymbols = poloniex.fetch_ticker(s)
                    dataSymbols = allData[s]
                    coinBalance = totalBalance.get(s.split("/")[0], 0)
                    volume = int(float(dataSymbols["info"]["baseVolume"]))
                    ask = dataSymbols["info"]["lowestAsk"]
                    bid = dataSymbols["info"]["highestBid"]
                    last = float(dataSymbols["info"]["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(
                        ["poloniex", s, coinBalance, ask, bid, volume])
                except:
                    print("Poloniex couldn`t get " + s)
                    continue
    except Exception as e:
        print(str(e)[:150])
    return (result)
Beispiel #22
0
def fetch_exchange_data(exchange_name):
    bitstamp = ccxt.bitstamp()
    bitmex = ccxt.bitmex()
    bitfinex = ccxt.bitfinex2()
    bittrex = ccxt.bittrex()
    okcoin = ccxt.okcoinusd()
    kraken = ccxt.kraken()
    binance = ccxt.binance()
    coss = ccxt.coss()
    kucoin = ccxt.kucoin2()
    poloniex = ccxt.poloniex()
    # theocean = ccxt.theocean()
    upbit = ccxt.upbit()
    dict_of_exchanges = {
        'kraken': kraken,
        'bitmex': bitmex,
        'bittrex': bittrex,
        'bitstamp': bitstamp,
        'bitfinex': bitfinex,
        'okcoin': okcoin,
        'binance': binance,
        'coss': coss,
        'kucoin': kucoin,
        'poloniex': poloniex,
        # 'theocean': theocean,
        'upbit': upbit
    }
    try:
        return dict(
            dict_of_exchanges[exchange_name].fetch_order_book('BTC/USD'))
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('XRP/USD'))
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('LTC/USD'))
        # add BitcoinCash
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('ETH/USD'))
    except Exception as ex:
        print('%s - erro: %s' % (exchange_name, ex))
        return {}
Beispiel #23
0
    async def manage_database(self):
        period = 1800  # 30 minutes
        num_periods = 25
        data_age = period * num_periods

        exchange = ccxt.poloniex()
        symbols = ['ETH/BTC', 'BCH/BTC']

        # Check if database is empty or stale

        cursor = self.db.cursor(prepared=True)
        query = """SELECT IFNULL(MAX(time), -1) FROM candlesticks"""
        cursor.execute(query)
        timestamp_highest = int(cursor.fetchone()[0])
        to_inform = collector__pb2.CandlestickSet()

        if timestamp_highest == -1:
            # Database is empty
            for symbol in symbols:
                since = int(time.time() - data_age)
                candlesticks = Collector.poll_candlesticks(
                    exchange, symbols, since)
                for c in candlesticks:
                    c[0] = int(c[0])
                    self.write_candlestick(c[0] / 1000, c[1], c[2], c[3], c[4],
                                           c[5], symbol, cursor)
                    to_inform.candlesticks.extend([
                        Candlestick(timestamp=int(c[0] / 1000),
                                    open=c[1],
                                    high=c[2],
                                    low=c[3],
                                    close=c[4],
                                    volume=c[5],
                                    symbol=symbol)
                    ])

        elif timestamp_highest < int(time.time() - period):
            # Database is stale (older than 30m)
            # if data is older than data_age, only pull data since then
            # otherwise pull all data since most recent stored data
            since = time.time() - data_age if timestamp_highest < time.time(
            ) - data_age else time.time() - period
            for symbol in symbols:
                candlesticks = Collector.poll_candlesticks(
                    exchange, symbols, int(since))
                for c in candlesticks:
                    self.write_candlestick(c[0] / 1000, c[1], c[2], c[3], c[4],
                                           c[5], symbol, cursor)
                    to_inform.candlesticks.extend([
                        Candlestick(timestamp=int(c[0] / 1000),
                                    open=c[1],
                                    high=c[2],
                                    low=c[3],
                                    close=c[4],
                                    volume=c[5],
                                    symbol=symbol)
                    ])

        # Give candlesticks to navigator and web  TODO do something smart here to prevent duplicate data in navigator
        print(time.strftime('%I:%M%p'),
              ": Giving initial candlesticks to Navigator...")
        response_navigator = self.navigator_stub.PutCandlesticks(to_inform)
        # response_web = self.web_stub.InformCandlesticks(to_inform)
        print(time.strftime('%I:%M%p'), ':', response_navigator)

        # Do poll to database every 15 minutes and write to db and give to navigator
        while True:
            for symbol in symbols:
                to_inform = collector__pb2.CandlestickSet()
                candlesticks = Collector.poll_candlesticks(
                    exchange, symbols, int(time.time()))
                for c in candlesticks:
                    c[0] = int(c[0])
                    self.write_candlestick(c[0] / 1000, c[1], c[2], c[3], c[4],
                                           c[5], symbol, cursor)
                    to_inform.candlesticks.extend([
                        Candlestick(timestamp=int(c[0] / 1000),
                                    open=c[1],
                                    high=c[2],
                                    low=c[3],
                                    close=c[4],
                                    volume=c[5],
                                    symbol=symbol)
                    ])
            if len(to_inform.candlesticks) != 0:
                print(time.strftime('%I:%M%p'),
                      ": Giving candlesticks to Navigator...")
                response_navigator = self.navigator_stub.PutCandlesticks(
                    to_inform)
                # response_web = self.web_stub.InformCandlesticks(to_inform)
                print(time.strftime('%I:%M%p'), response_navigator)
            else:
                print(time.strftime('%I:%M%p'),
                      ": There are no new candlesticks.")
            print(time.strftime('%I:%M%p'), ": Waiting 5 minutes....")
            await asyncio.sleep(period / 6)
Beispiel #24
0
BASE_CURRENCY = 'ETH'
DISPLAY_NUMBER_OF_ALTCOINS = 100  # TODO
MIN_VOLUME = 10  # TODO
PROFIT_RATE_THRESHOLD = 1.0 / 100  # TODO: ex) 0.01 = 1%
EXCHANGES = [
    # # 1. Bitfinex (sometimes raises json.decoder.JSONDecodeError)
    # (ccxt.bitfinex({
    #     'apiKey': BITFINEX_KEY,
    #     'secret': BITFINEX_SECRET,
    # }), 'https://www.bitfinex.com/trading/{0}{1}'),
    # # 2. Bithumb
    # (ccxt.bithumb(), 'https://www.bithumb.com/trade/order/{0}'),
    # 3. Bittrex
    (ccxt.bittrex(), 'https://bittrex.com/Market/Index?MarketName={1}-{0}'),
    # 4. Poloniex
    (ccxt.poloniex(), 'https://poloniex.com/exchange#{1}_{0}'),
    # # 5. GDAX
    # (ccxt.gdax(), 'https://www.gdax.com/trade/{0}-{1}'),
    # # 7. Kraken
    # (ccxt.kraken(), 'https://www.kraken.com/charts'),
    # 8. HitBTC
    (ccxt.hitbtc2(), 'https://hitbtc.com/exchange/{0}-to-{1}'),
    # # 9. Bitstamp (sometimes raises HTTPError 404: NOT FOUND)
    # (ccxt.bitstamp(), 'https://www.bitstamp.net/'),
    # 10. bitFlyer (need apiKey and secret)
    # (ccxt.bitflyer(), 'https://lightning.bitflyer.jp/trade/{0}{1}'),
    # # 12. Gemini
    # (ccxt.gemini(), 'https://gemini.com/marketplace/'),
    # # 14. Binance
    # (ccxt.binance({
    #     'apiKey': BINANCE_KEY,
# -*- coding: utf-8 -*-

import os
import sys
import psutil

# -----------------------------------------------------------------------------

this_folder = os.path.dirname(os.path.abspath(__file__))
root_folder = os.path.dirname(os.path.dirname(this_folder))
sys.path.append(root_folder + '/python')
sys.path.append(this_folder)

# -----------------------------------------------------------------------------

import ccxt  # noqa: E402

# -----------------------------------------------------------------------------

exchange = ccxt.poloniex({
    'enableRateLimit': True,
})

while True:
    orderbook = exchange.fetch_order_book('ETH/BTC')
    process = psutil.Process(os.getpid())
    print(exchange.iso8601(exchange.milliseconds()), process.memory_info().rss)
Beispiel #26
0
import time
import ccxt as ccxt

pairs = ['ETH/BTC']

exchange = ccxt.poloniex({
    'apiKey': '',
    'secret': '',
    'enableRateLimit': True,
})

orderbook = {}

# -----------------------------------------------------------------------------

def makeOrderbook(orderbook, pairs):
    for pair in pairs:
        pair = ''.join(e for e in pair if e.isalnum())
        orderbook[pair] = {'bids': {'price': 0,
                                    'amount': 0
                                    },
                           'asks': {'price': 0,
                                    'amount': 0}}


def fetchOB(symbol):
    try:
        ticker = exchange.fetch_order_book(symbol)
        if isinstance(ticker, type(None)):
            fetchOB(symbol)
        else:
sys.path.append(root + '/python')

import ccxt  # noqa: E402

exchange = ccxt.poloniex({
    #
    # ↓ The "proxy" property setting below is for CORS-proxying only!
    # Do not use it if you don't know what a CORS proxy is.
    # https://github.com/ccxt/ccxt/wiki/Install#cors-access-control-allow-origin
    # You should only use the "proxy" setting if you're having a problem with Access-Control-Allow-Origin
    # In Python you rarely need to use it, if ever at all.
    #
    # 'proxy': 'https://cors-anywhere.herokuapp.com/',
    #
    # ↓ On the other hand, the "proxies" setting is for HTTP(S)-proxying (SOCKS, etc...)
    # It is a standard method of sending your requests through your proxies
    # This gets passed to the `python-requests` implementation directly
    # You can also enable this with environment variables, as described here:
    # http://docs.python-requests.org/en/master/user/advanced/#proxies
    # The environment variables should be set before importing ccxt (!)
    # This is the setting you should be using with synchronous version of ccxt in Python 2 and 3
    #
    'proxies': {
        'http': 'http://10.10.1.10:3128',
        'https': 'http://10.10.1.10:1080',
    },
})

# your code goes here...

pprint(exchange.fetch_ticker('ETH/BTC'))
Beispiel #28
0
import ccxt

exchanges = {
    'binance': ccxt.binance(),
    # 'kucoin': ccxt.kucoin(),
    'bittrex': ccxt.bittrex(),
    'bitstamp': ccxt.bitstamp(),
    'poloniex': ccxt.poloniex(),
    # 'bitforex': ccxt.bitforex(),
    # 'hitbtc': ccxt.hitbtc(),
}
Beispiel #29
0
    def handle(self, *args, **options):
        """Get the latest currency rates."""
        count = 0
        result = ''

        print('Attempting to connect to etherdelta API websocket...')
        ws = create_connection(
            'wss://socket.etherdelta.com/socket.io/?transport=websocket')
        print('Sending getMarket message...')
        ws.send('42["getMarket",{}]')
        print('Sent getMarket message! Waiting on proper response...')

        # Wait for the getMarket response or timeout at 30.
        while (result[:2] != "42" or count > 60):
            result = ws.recv()
            count += 1
            print(count)

        ws.close()  # Close the websocket connection.

        try:
            # Attempt to format the response data.
            market_results = json.loads(result[2:])
            tickers = market_results[1]['returnTicker']
        except ValueError:
            tickers = {}
            print('Failed to retrieve etherdelta ticker data!')

        # etherdelta
        for pair, result in tickers.items():
            from_currency = pair.split('_')[0]
            to_currency = pair.split('_')[1]

            from_amount = 1
            to_amount = (result['bid'] + result['ask']) / 2
            try:
                ConversionRate.objects.create(
                    from_amount=from_amount,
                    to_amount=to_amount,
                    source='etherdelta',
                    from_currency=from_currency,
                    to_currency=to_currency,
                )
                print('Etherdelta: {}=>{}:{}'.format(from_currency,
                                                     to_currency, to_amount))
            except Exception as e:
                print(e)

        tickers = ccxt.poloniex().load_markets()
        for pair, result in tickers.items():
            from_currency = pair.split('/')[0]
            to_currency = pair.split('/')[1]

            from_amount = 1
            try:
                to_amount = (float(result['info']['highestBid']) +
                             float(result['info']['lowestAsk'])) / 2
                ConversionRate.objects.create(
                    from_amount=from_amount,
                    to_amount=to_amount,
                    source='poloniex',
                    from_currency=from_currency,
                    to_currency=to_currency,
                )
                print('Poloniex: {}=>{}:{}'.format(from_currency, to_currency,
                                                   to_amount))
            except Exception as e:
                print(e)

        for b in Bounty.objects.all():
            print('refreshed {}'.format(b.pk))
            try:
                b._val_usd_db = b.value_in_usdt
                b.save()
            except Exception as e:
                print(e)
                b._val_usd_db = 0
                b.save()
Beispiel #30
0
        }.get(param, "")
        print("        '{}': fields.{}(required=False, description='{}', example='{}'),".format(param, fieldType, param, example))
    print("    },")


def generate_api(exchange: ccxt.Exchange):
    name = exchange.__class__.__name__
    sigs = get_signatures(exchange)
    methods = list(sigs.keys())

    env = Environment(loader=FileSystemLoader("../apis"))
    template = env.get_template("api.py.jinja2")

    text = template.render({"exchange_name": name, "methods": methods})

    filename = "../apis/{}.py".format(name)
    with open(filename, "w") as f:
        f.write(text)

    print("Generated '{}'".format(filename))


if __name__ == '__main__':
    generate_api(ccxt.bittrex())
    generate_api(ccxt.poloniex())
    generate_api(ccxt.bitflyer())

    sigs = get_signatures(ccxt.bittrex())
    for method, sig in sigs.items():
        signature_to_model_text(method, sig)