Ejemplo n.º 1
0
 def __init__(self):
     #try except
     #Initiate exchange data with objects for each exchange
     binance = ccxt.binance()
     bittrex = ccxt.bittrex()
     bitfinex = ccxt.bitfinex()
     kraken = ccxt.kraken()
     kucoin = ccxt.kucoin()
     #Dictionary with the ccxt objects
     self.exchanges = {
         'binance': binance,
         'bittrex': bittrex,
         'bitfinex': bitfinex,
         'kraken': kraken,
         'kucoin': kucoin
     }
     #Get a list of tickers from Binance exchange to use throughout
     self.ticker_list = []
     self.get_tickers_list()
     #CREATE A DATAFRAME FOR THE PRICE AND VOLUME DATA
     self.volume = pd.DataFrame(index=self.ticker_list,
                                columns=list(self.exchanges.keys()))
     self.pricedf = pd.DataFrame(index=self.ticker_list,
                                 columns=list(self.exchanges.keys()))
     self.spread = pd.DataFrame(index=self.ticker_list,
                                columns=list(self.exchanges.keys()))
Ejemplo n.º 2
0
def kuCoin():
    symbol = 'DBC/ETH'
    exchange = ccxt.kucoin()
    markets = exchange.load_markets()
    ticker = exchange.fetch_ticker(symbol.upper())
    print(ticker)
    avgPrice = (ticker['bid'] + ticker['ask']) / 2
    print(avgPrice)
    return avgPrice
Ejemplo n.º 3
0
def load_exchange():
    try:
        exchange = ccxt.kucoin()
        market = exchange.load_markets()
    except ccxt.RequestTimeout:
        time.sleep(DELAY)
        exchange, market = load_exchange()

    return exchange, market
Ejemplo n.º 4
0
def load_exchange():
    try:
        exchange = ccxt.kucoin()
        market = exchange.load_markets()
    except ccxt.RequestTimeout:
        wait()
        exchange, market = load_exchange()

    return exchange, market
Ejemplo n.º 5
0
def load_exchange():
    '''loads exchange and the market information.
    '''
    try:
        exchange = ccxt.kucoin()
        market = exchange.load_markets()
    except ccxt.RequestTimeout:
        wait()
        exchange, market = load_exchange()

    return exchange, market
Ejemplo n.º 6
0
def get_kucoin_connection(key, secret):
    try:
        kucoin = ccxt.kucoin({
            'apiKey': key,
            'secret': secret
        })
        log("INFO", "Successfully established connection to KuCoin API")
        return kucoin
    except Exception as e:
        log("ERROR", f"Failed to establish connection to KuCoin API: {e}")

    return
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def load_exchange():
    '''loads exchange and the market information.
    '''
    try:
        exchange = ccxt.kucoin()
        market = exchange.load_markets()
    except (ccxt.RequestTimeout, ccxt.ExchangeError) as error:
        print("Be patient, we are trying to connect to the exchange.")
        print("In the mean while, check your internet connection.")
        print("Error:", error)
        wait()
        exchange, market = load_exchange()
    return exchange, market
Ejemplo n.º 9
0
    def fetch_data(market_pair,
                   total_days=365,
                   timeframe='5m',
                   exchange=ccxt.kucoin()):

        ohlcv_data = []
        partial_list = []

        time_end = datetime.datetime.now()
        api_parts = range(1, int(total_days / 5) + 1)

        for i in api_parts:
            days = 5 * i
            time_start = time_end - datetime.timedelta(days)
            time_start = int(time_start.timestamp() * 1000)

            partial_list = exchange.fetch_ohlcv(market_pair,
                                                timeframe,
                                                since=time_start)
            partial_list = list(reversed(partial_list))
            ohlcv_data.extend(partial_list)

            clear_output()
            time_remaining = api_parts[-1] - i
            print('Slot ',
                  i,
                  ' was appended to the list ',
                  market_pair,
                  '. Only ',
                  time_remaining,
                  ' of ',
                  api_parts[-1],
                  ' to complete.',
                  sep='')
            time.sleep(
                5
            )  # aumentar o número de segundos caso surja alta restrição de request/tempo no futuro
            '''
            verifica último item para saber se alcançou início da API. 
            1505587800000 = Saturday, September 16, 2017 6:50:00 PM
            '''
            if partial_list[-1][0] == 1505587800000:
                print('Extração de dados terminou.')
                break
        return ohlcv_data
Ejemplo n.º 10
0
def kucoinAgg(symbols):
    result = []
    try:
        kucoin = ccxt.kucoin({
            'apiKey': 'apiKey',
            'secret': 'secret',
            'options': {
                'adjustForTimeDifference': True
            }
        })
        totalBalance = kucoin.fetch_balance()["free"]
        exchangeSymbols = kucoin.symbols
        checkSymbols = list(np.intersect1d(exchangeSymbols, symbols))
        allData = kucoin.fetch_tickers(checkSymbols)
        ethPrice = kucoin.fetch_ticker("ETH/USDT")["last"]
        btcPrice = kucoin.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(["kucoin", s, coinBalance, ask, bid, volume])
            except:
                print("Kucoin couldn`t get " + s)
                continue
    except Exception as e:
        print(str(e)[:150])
    return (result)
Ejemplo n.º 11
0
import pandas as pd

########
# Params
########
ccy = 'WAVES'

######
# Main
######
apiKey = API_KEYS_KU[0]
apiSecret = API_SECRETS_KU[0]
apiPassword = API_PASSWORDS_KU[0]
d = {
    'apiKey': apiKey,
    'secret': apiSecret,
    'password': apiPassword,
    'enableRateLimit': True,
    'nonce': lambda: ccxt.Exchange.milliseconds()
}
for proxy in PROXIES_KU:
    z = 'socks5://' + proxy + ':1080'
    print(z)
    d['proxies'] = {'http': z, 'https': z}

    ku = ccxt.kucoin(d)
    ku.options['recvWindow'] = 50000
    df = pd.DataFrame(
        ku.futuresPrivate_get_positions()['data']).set_index('symbol')
    print(df.loc[ccy + 'USDTM']['currentQty'])
Ejemplo n.º 12
0
def is_trair(trair_candidate):
    # assuming that all currencies appear twice means we have a trair
    currency_counts = Counter(chain.from_iterable(trair_candidate))
    return set(currency_counts.values()) == {2}

def format_trairs(trairs):
    trair= []
    for i in range(len(trairs)):
        t_trair = []
        for j in range(len(trairs[i])):
            t_trair.append(trairs[i][j][0]+'/'+trairs[i][j][1])
        print(t_trair)
        trair.append(t_trair)

    return (trair)

exchange = ccxt.kucoin()
market = exchange.load_markets()
exchange_pairs = exchange.symbols

raw_pairs = list(filter(lambda x: not '.d' in x, exchange_pairs))

pairs = map(parse_pair, raw_pairs)
trair_candidates = combinations(pairs, r=3)
#filter the actual trairs from all trair_candidates
trairs = list(filter(is_trair,trair_candidates))
trair = format_trairs(trairs)


Ejemplo n.º 13
0
    def update_withdrawal_fees(self, exchanges):
        """
        Update withdrawal fees data on self_coin_list
        @exchanges: CoinList.BINANCE | CoinList.BITTREX | CoinList.POLONIEX
        """

        bin_list, bit_list, polo_list = [], [], []
        kraken_dict = {}

        if CoinList.BINANCE in exchanges:
            bin = BinanceAPIClient()
            bin_list = bin.get_withdrawal_fees()

        if CoinList.BITTREX in exchanges:
            bit = BittrexAPIClient()
            bit_list = bit.get_withdrawal_fees()

        if CoinList.POLONIEX in exchanges:
            polo = PoloniexAPIClient()
            polo_list = polo.get_withdrawal_fees()

        if CoinList.KRAKEN in exchanges:
            kraken = ccxt.kraken()
            kraken_dict = kraken.fees['funding']['withdraw']

        if CoinList.KUCOIN in exchanges:
            kucoin = ccxt.kucoin()
            kucoin_dict = kucoin.fees['funding']['withdraw']

        for coin in self.coin_list:
            for bin_coin in bin_list:
                if (coin.ticker == bin_coin['ticker']):
                    coin.binance_fee = bin_coin['withdrawal_fee']
                    coin.binance_fee_usd = round(
                        float(coin.binance_fee) * float(coin.price_usd), 2)
                    break

            for bit_coin in bit_list:
                if (coin.ticker == bit_coin['ticker']):
                    coin.bittrex_fee = bit_coin['withdrawal_fee']
                    coin.bittrex_fee_usd = round(
                        float(coin.bittrex_fee) * float(coin.price_usd), 2)
                    break

            for polo_coin in polo_list:
                if (coin.ticker == polo_coin['ticker']):
                    coin.poloniex_fee = polo_coin['withdrawal_fee']
                    coin.poloniex_fee_usd = round(
                        float(coin.poloniex_fee) * float(coin.price_usd), 2)
                    break

            for key, value in kraken_dict.items():
                if (coin.ticker == key):
                    coin.kraken_fee = value
                    coin.kraken_fee_usd = round(
                        float(coin.kraken_fee) * float(coin.price_usd), 2)
                    break

            for key, value in kucoin_dict.items():
                if (coin.ticker == key):
                    coin.kucoin_fee = value
                    coin.kucoin_fee_usd = round(
                        float(coin.kucoin_fee) * float(coin.price_usd), 2)
                    break

plt.style.use ('seaborn-white')
plt.rcParams["figure.figsize"] = [15,6]


apiKey = "--------------------------------" #@param [""] {allow-input: true}
secret = "---------------------------"  #@param {type:"string"}
subaccount = "---- main = 0 , subacc ---- " #@param ["---- main = 0 , subacc ---- "] {allow-input: true}
password = "******" #@param ["----------------------"] {allow-input: true}




exchange = ccxt.kucoin({
    'apiKey' :apiKey,'secret' : secret,'subaccount':subaccount,'password':password,'enbleRateLimit':True
    }) 
   
if subaccount == "0":
  print("This is Main Account")
else:
  exchange.headers = {
   'KUCOIN-SUBACCOUNT': subaccount,
  }

#@title ฟังก์ชั่น คำนวนการใช้งาน
def getBalance():
    print("PORT BALANCE =",exchange.fetch_balance())

def getfreeCol():
    freeCol = exchange.fetchFreeBalance()['result'][0]['free']
Ejemplo n.º 15
0
def KUM_with_ip_init():
  return ccxt.kucoin({'apiKey': API_KEY_KUM_WITH_IP, 'secret': API_SECRET_KUM_WITH_IP, 'password': API_PASSWORD_KUM_WITH_IP, 'enableRateLimit': True, 'nonce': lambda: ccxt.Exchange.milliseconds()})
Ejemplo n.º 16
0
print('python', sys.version)
print('CCXT Version:', ccxt.__version__)

binance = ccxt.binance({
    "apiKey": 'YOUR_BINANCE_API_KEY',
    "secret": 'YOUR_BINANCE_SECRET',
    'options': {
        'fetchCurrencies': True,
    },
})
binance.verbose = True

kucoin = ccxt.kucoin({
    'apiKey': 'YOUR_KUCOIN_API_KEY',
    'secret': 'YOUR_KUCOIN_SECRET',
    'password': '******',
})
kucoin.verbose = True

binance.load_markets()
kucoin.load_markets()

code = 'USDT'
amount = 40

params = {'network': 'TRC20'}

deposit = binance.fetchDepositAddress(code, params)

print('-----------------------------------------------------------')
Ejemplo n.º 17
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'],
        'enableRateLimit': True,
    })

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

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

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

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

    kucoin = ccxt.kucoin({
        'apiKey': api_keys.kucoin['apiKey'],
        'secret': api_keys.kucoin['secret'],
        'enableRateLimit': True,
    })

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

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

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

    exchanges = [
        coinbasepro, poloniex, bittrex, binance, bitfinex, kucoin, bitmex, okex
    ]
    timing_limits = [.35, .35, 1, .35, 2, 1, 1,
                     .35]  # requesting period limit per exchange
    # timing_limits = [0, 0, 0, 0, 0, 0, 0, 0]  # rateLimit Enabled on exchange

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

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

    return exchanges
Ejemplo n.º 18
0
binance = ccxt.binance({'enableRateLimit': True})
hitbtc = ccxt.hitbtc2({'enableRateLimit': True})
coinbasepro = ccxt.coinbasepro({
    'enableRateLimit': True,
})
gemini = ccxt.gemini({
    'enableRateLimit': True,
})
bitfinex = ccxt.bitfinex({
    'enableRateLimit': True,
})
livecoin = ccxt.livecoin({
    'enableRateLimit': True,
})
kucoin = ccxt.kucoin({
    'enableRateLimit': True,
})
cex = ccxt.cex({
    'enableRateLimit': True,
})
bitstamp = ccxt.bitstamp({
    'enableRateLimit': True,
})

binance_ltc_address = 'LLmWdKju3aHzS8q5azoVGSfPV6NY6a4PvY'
exmo_ltc_address = 'LThC9vNBvyJz7UesBAmpMaJNfHFhxXqhb6'
#----------XRP------------
hitbtc_xrp_deposit_address = 'rhL5Va5tDbUUuozS9isvEuv7Uk1uuJaY1T'
hitbtc_xrp_tag = '1492555998'

exmo_xrp_deposit_address = 'rUocf1ixKzTuEe34kmVhRvGqNCofY1NJzV'
Ejemplo n.º 19
0
import ccxt
import pandas as pd

exchange = ccxt.kucoin({
    'apiKey': '********',
    'secret': '************',
    'password': '******',
    'enableRateLimit': True,
})

symbol = 'BNB/USDT'
typee = 'limit'  # or 'market'
side = 'sell'  # or 'buy'
amount = 0.001
price = 20.00  # or None

params = {
    'recvWindow': 50000
}

#order = exchange.fetch_my_trades(symbol ='BNB/USDT', params = params)
#order = exchange.create_order(symbol, typee, side, amount, price, params)
#print(type(order))
#print(order['id'])
#print(order)


#balance = exchange.fetch_balance(params)
#df_balance = pd.DataFrame.from_dict(balance['info']['data']).set_index(['type', 'currency'])
#df_balance['balance'] = df_balance.balance.astype(float)
#print(df_balance.filter(like='trade', axis=0).loc[df_balance.balance > 0])
Ejemplo n.º 20
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
Ejemplo n.º 21
0
# -*- coding: utf-8 -*-

import os
import sys
from pprint import pprint

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

import ccxt  # noqa: E402

exchange = ccxt.kucoin({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_API_SECRET',
    'password': '******',
})

markets = exchange.load_markets()

exchange.verbose = True  # uncomment for debugging purposes if necessary

for code in ['TLOS']:  # exchange.currencies.keys():
    response = exchange.public_get_currencies_currency({'currency': code})
    currency = exchange.safe_value(response, 'data')
    if currency:
        # pprint(currency)
        chains = exchange.safe_value(currency, 'chains')
        for chain in chains:
            chainName = exchange.safe_string(chain, 'chainName')
            try:
Ejemplo n.º 22
0
                    get_single_price(b, q, e)
                    pairs.append(b + '-' + q)
                except PairNotListedError:
                    pass

    return pairs


def get_order_books(base, quote, client):
    """ Batch version of fetch order book ccxt function """
    if isinstance(base, str):
        base = [base]
    if isinstance(quote, str):
        quote = [quote]

    order_books = {}
    for b in base:
        for q in quote:
            pair = b + '/' + q
            order_books[pair] = client.fetch_order_book(pair)

    # NOTE: order book lengths are different for different clients
    return order_books


if __name__ == '__main__':
    ob = get_order_books('LTC', 'BTC', ccxt.kucoin())['LTC/BTC']
    print(ob)
    print(len(ob['asks']), len(ob['bids']))

Ejemplo n.º 23
0
    def run(self):
        self.client = Client(api_key=self.config['BINANCE']['KEY'],
                             api_secret=self.config['BINANCE']['SECRET'])
        if self.args.mode == "trading":
            logger.info(
                "START TRADE | symbol: {}, btc amount: {}, targets: {}, stoploss price: {}, trailing: {}, trailing price: {}"
                .format(self.args.symbol, self.args.btc_amount,
                        self.args.targets, self.args.immediate_stoploss,
                        self.args.use_trailing, self.args.trailing_stoploss))
            bm = BinanceSocketManager(self.client)
            self.conn_key = bm.start_symbol_ticker_socket(
                self.args.symbol, self.process_message)
            bm.start()
        elif self.args.mode == "analysis":
            alltickers = self.client.get_ticker()
            interval = "1h"
            exchange = ccxt.binance({
                'apiKey': self.config['BINANCE']['KEY'],
                'secret': self.config['BINANCE']['SECRET']
            })
            for ticker in alltickers:
                if float(ticker['priceChangePercent']) > 2 and (
                        "BTC" in ticker['symbol']):
                    data_base = exchange.fetch_ohlcv(
                        ticker['symbol'].split("BTC")[0] + "/BTC",
                        interval,
                        limit=100)
                    df = pd.DataFrame(data_base,
                                      columns=[
                                          'date', 'open', 'high', 'low',
                                          'close', 'volume'
                                      ])
                    df["date"] = pd.to_datetime(
                        df["date"], unit='ms').dt.strftime('%Y-%m-%d %H:%M')
                    self.save_analysis(df, ticker['symbol'], interval,
                                       ticker['priceChangePercent'])
        elif self.args.mode == "hamster":
            mongo_client = MongoClient('mongodb://localhost:27017/')
            db = mongo_client.projectlife
            self.previous_response = "initial"
            timeout = 30
            exchanges = dict()
            exchanges['binance'] = ccxt.binance({
                'apiKey':
                self.config['BINANCE']['KEY'],
                'secret':
                self.config['BINANCE']['SECRET']
            })
            exchanges['kucoin'] = ccxt.kucoin({
                'apiKey':
                self.config['KUCOIN']['KEY'],
                'secret':
                self.config['KUCOIN']['SECRET']
            })
            exchanges['bittrex'] = ccxt.bittrex({
                'apiKey':
                self.config['BITTREX']['KEY'],
                'secret':
                self.config['BITTREX']['SECRET']
            })
            exchanges['poloniex'] = ccxt.poloniex()

            def doWork():
                responses = []
                try:
                    url = 'https://www.mininghamster.com/api/v2/' + self.config[
                        'HAMSTER']['API']
                    responses = requests.get(url).json()
                    if len(responses) > 0:
                        for response in responses:
                            symbol = response['market'].split(
                                "BTC-")[1] + "/BTC"
                            bid, ask = self.get_prices(
                                exchanges[response['exchange']], symbol)
                            if response['signalmode'] == "buy":
                                result_buy = db.hamster.find_one({
                                    "signalID":
                                    response['signalID'],
                                    "signalmode":
                                    "buy"
                                })
                                if result_buy == None:
                                    response['buy_price'] = ask
                                    db.hamster.insert_one(response)
                                    self.send_telegram(str(response))
                            elif response['signalmode'] == "sell":
                                result_sell = db.hamster.find_one({
                                    "signalID":
                                    response['signalID'],
                                    "signalmode":
                                    "sell"
                                })
                                if result_sell == None:
                                    result_buy = db.hamster.find_one({
                                        "signalID":
                                        response['signalID'],
                                        "signalmode":
                                        "buy"
                                    })
                                    if result_buy != None:
                                        response['sell_price'] = bid
                                        response['profit'] = self.pct_change(
                                            result_buy['buy_price'], bid)
                                        db.hamster.insert_one(response)
                                        self.send_telegram(str(response))

                except BaseException as e:
                    print(e)
                pass

            lx = task.LoopingCall(doWork)
            lx.start(timeout)
            reactor.run()
        elif self.args.mode == "datacollect":
            client = MongoClient('mongodb://localhost:27017/')
            db = client.projectlife
            self.db_collection = db[self.args.symbol]
            bm = BinanceSocketManager(self.client)
            self.conn_key = bm.start_symbol_ticker_socket(
                self.args.symbol, self.process_datacollect_message)
            bm.start()
Ejemplo n.º 24
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.bxinth(),
        ccxt.ccex(),
        ccxt.cex(),
        ccxt.chbtc(),
        ccxt.chilebit(),
        ccxt.coincheck(),
        ccxt.coinfloor(),
        ccxt.coingi(),
        ccxt.coinmarketcap(),
        ccxt.coinmate(),
        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.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
Ejemplo n.º 25
0
import ccxt
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:
Ejemplo n.º 26
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'],
        'enableRateLimit': True,
    })

    cex = ccxt.cex({
        'apiKey': api_keys.cex['apiKey'],
        'secret': api_keys.cex['secret'],
        'enableRateLimit': True,
    })

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

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

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

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

    kucoin = ccxt.kucoin({
        'apiKey': api_keys.kucoin['apiKey'],
        'secret': api_keys.kucoin['secret'],
        'enableRateLimit': True,
    })

    kraken = ccxt.kraken({
        'apiKey': api_keys.kraken['apiKey'],
        'secret': api_keys.kraken['secret'],
        'enableRateLimit': True,
        'options': {  # ←--------------------- inside 'options' subkey
            'fetchMinOrderAmounts': False,  # ←---------- set to False 
        }
    })

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

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

    exchanges = [
        coinbasepro, cex, poloniex, bittrex, binance, bitfinex, kucoin, kraken,
        okex, bitmex
    ]

    return exchanges
Ejemplo n.º 27
0
token_to_prices = calculate_token_to_prices(
  bittrex,
  token_to_markets,
  bittrex_btc_usd_last,
  bittrex_eth_usd_last,
  bittrex_eth_btc_last,
  bittrex_all_tickers
)

token_exchanges = generate_token_exchanges('bittrex', token_to_prices)
update_token_exchanges(token_exchanges)



### Kucoin ###
kucoin = ccxt.kucoin()
kucoin_all_tickers = kucoin.fetchTickers()

kucoin_btc_usd_last = kucoin_all_tickers['BTC/USDT']['last']
kucoin_eth_usd_last = kucoin_all_tickers['ETH/USDT']['last']
kucoin_eth_btc_last = kucoin_all_tickers['ETH/BTC']['last']

token_to_markets = parse_tokens_to_markets(kucoin.fetchMarkets())
token_to_prices = calculate_token_to_prices(
  kucoin,
  token_to_markets,
  kucoin_btc_usd_last,
  kucoin_eth_usd_last,
  kucoin_eth_btc_last,
  kucoin_all_tickers
)
Ejemplo n.º 28
0
import ccxt
import pandas as pd

exchange = ccxt.kucoin({
    'apiKey': '5f06d59e3988760006e3efbd',
    'secret': '35f65889-d94b-4f57-b930-bbb3940784bc',
    'password': '******'
})

#def ordercreate(status,amount,price):
#   exchange.create_order('BNB/USDT','limit',status,amount,price)

#print(exchange.fetch_balance ()) #look at how much balance

#print(exchange.fetch_total_balance())
#print(exchange.fetch_ticker('BNB/USD')['last'])

#ordercreate('buy',0.001,16.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.kucoin({
    "apiKey": "YOUR_API_KEY",
    "secret": "YOUR_SECRET",
    "password": "******"
})

symbol = 'ETH/USDT'
now = exchange.milliseconds()
day = 24 * 3600 * 1000
week = 7 * day
since = now - 365 * day  # start one year back
limit = 20

while since < now:

    end = min(since + week, now)
    params = {'endAt': end}
    orders = exchange.fetch_closed_orders(symbol, since, limit, params)
    print(exchange.iso8601(since), '-', exchange.iso8601(end), len(orders),
          'orders')
Ejemplo n.º 30
0
def calc():

    bitfinex = ccxt.bitfinex()
    marketsBf = bitfinex.load_markets()

    cex = ccxt.cex()
    kucoin = ccxt.kucoin()
    poloniex = ccxt.poloniex()
    bittrex = ccxt.bittrex()

    FEE = 1.02  # fee for every trade (2%)
    Diff = 0.6  # 1 % arbitrage to execute
    curr = [
        "ETH/BTC", "OMG/BTC", "LTC/BTC", "DASH/BTC", "ETC/BTC", "OMG/BTC"
    ]  #  "LTC/BTC", "DASH/BTC", "ETC/BTC", "OMG/BTC", "BCH/BTC"     currencies to trade if arbitrage is found
    exc = [
        bitfinex, kucoin, bittrex, cex
    ]  #  cex ,kucoin , bittrex   exchanges to trade on for the function calls

    def getAsk(market, sym):
        orderbook = market.fetch_order_book(sym)
        ask = orderbook['asks'][0][0] if len(orderbook['asks']) > 0 else None
        return ask

    def getBid(market, sym):
        orderbook = market.fetch_order_book(sym)
        bid = orderbook['bids'][0][0] if len(orderbook['bids']) > 0 else None
        return bid

    def compare():
        print("Arbitrage Trader starting up...")
        yon_file = open("yon.txt", "r")
        yon = yon_file.read()
        yon_file.close
        n = 0
        while n <= (len(curr) - 1):
            print("Starting Arbitrage checking for ", curr[n])
            pairpart1 = curr[n]
            m = 0
            while m <= (len(exc) - 1):
                #print "m = " + str(m)
                k = 0
                while k <= (len(exc) - 1):
                    #print "k = " + str(k)
                    try:
                        if (yon == "1"):
                            sprice = getBid(exc[m], curr[n])
                            bprice = getAsk(exc[k], curr[n])
                        else:
                            sprice = getBid(exc[k], curr[n])
                            bprice = getAsk(exc[m], curr[n])

                    except Exception:
                        pass

                    #print ("Sell price = " , str(sprice) , " on " , exc[m].id)
                    #print ("Buy price  = " , str(bprice) , " on " , exc[k].id)

                    if (float(bprice) < float(sprice)):
                        #print ("Opportunity to buy " , curr[n] , " for ", str(bprice), " on ",exc[k]," and sell for " , str(sprice) , " on " , exc[m])
                        yie = ((float(sprice) - float(bprice)) /
                               float(sprice)) * 100.0
                        #print ("Yield before trading costs would be: ",str(yie),"%")

                    if (((float(sprice) - float(bprice)) / float(sprice)) *
                            100.0 > Diff):
                        # make_trade(exc[k], "buy", amount1, pairpart1, "btc", bprice)
                        # make_trade(exc[m], "sell", amount1, pairpart1, "btc", sprice)
                        #printouts for debugging
                        print("price on ", exc[m].id, " for ", curr[n], " is ",
                              str(sprice), " BTC")
                        print("price on ", exc[k].id, " for ", curr[n], " is ",
                              str(bprice), " BTC")
                        print(
                            "executing trade at a win per 1", curr[n], " of ",
                            str(
                                round(((sprice * 0.998) - (bprice * 1.002004)),
                                      8)), "BTC")
                        profit = str(
                            round(
                                100 * (((sprice + bprice) +
                                        (sprice * 0.998) - bprice * 1.002004) -
                                       (sprice + bprice)) / (sprice + bprice),
                                2))
                        print("profit %", profit)
                        with open("log.txt", "a") as text_file:
                            print(
                                f"{curr[n]}      {exc[m].id}      {sprice}    Sell",
                                file=text_file)
                            print(
                                f"{curr[n]}      {exc[k].id}      {bprice}    Buy",
                                file=text_file)
                            print(
                                f"-{exc[k].id}'den alındı {exc[m].id} 'de satıldı-----yön:{yon}------- Profit % {profit}\n",
                                file=text_file)
                            print(f" yön: {yon}")
                            text_file.close
                        yon_filer = open("yon.txt", "w")
                        if yon == "1":
                            yon_filer.write("0")
                        else:
                            yon_filer.write("1")
                        yon_filer.close

                    k += 1
                m += 1
            n += 1

    compare()