def okexData(): betime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) try: okex = ccxt.okex() coindata = list(okex.fetch_tickers().values()) columns = ['symbol', 'ask', 'bid', 'close', 'last', 'high', 'low', 'info', 'datetime'] df = pd.DataFrame(coindata) df = df[columns] df['vol'] = [i['vol'] for i in df['info']] df['exchange'] = 'okex' df = df.drop(['info'], axis=1) df['datetime'] = [i.replace('T', ' ') for i in df['datetime']] df['datetime'] = [i.replace('Z', '') for i in df['datetime']] 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:okex数据入库失败!\n' % betime) pass except: with open('coindataerr.log','a') as f: f.write('%s:okex数据获取失败!\n' % betime) pass
def _createExchangeObject(self, exchange): ''' Depricated ... now instantiating class using "eval" in __init__''' if exchange == "Binance": exchange = ccxt.binance() elif exchange == "Bitfinex": exchange = ccxt.bitfinex2() elif exchange == "Bitmex": exchange = ccxt.bitmex() elif exchange == "BitStamp": exchange = ccxt.binance() elif exchange == "Bittrex": exchange = ccxt.binance() elif exchange == "Bithumb": exchange = ccxt.bithumb() elif exchange == "CCTX": exchange = ccxt.cctx() elif exchange == "GDAX": exchange = ccxt.gdax() elif exchange == "HitBC": exchange = ccxt.hitbc() elif exchange == "Huobipro": exchange = ccxt.huobipro() elif exchange == "Kraken": exchange = ccxt.kraken() elif exchange == "OKEx": exchange = ccxt.okex() else: raise "Exception ExchangeCCXT::_createExchangeObject - ccxt Exchange not valid" return exchange
def _load_okex_ticker_data(symbol): okex = ccxt.okex({'verbose': True}) markets = okex.load_markets() ticker = okex.fetch_ticker(symbol) ticker.pop('info') ticker2 = {} ticker2['symbol'] = ticker.pop('symbol') ticker2['priceChange'] = ticker.pop('change') ticker2['priceChangePercent'] = ticker.pop('percentage') ticker2['weightedAvgPrice'] = ticker.pop('vwap') ticker2['prevClosePrice'] = ticker.pop('previousClose') ticker2['lastPrice'] = ticker.pop('last') ticker2['lastQty'] = 'none' ticker2['bidPrice'] = ticker.pop('bid') ticker2['bidQty'] = ticker.pop('bidVolume') ticker2['askPrice'] = ticker.pop('ask') ticker2['askQty'] = ticker.pop('askVolume') ticker2['openPrice'] = ticker.pop('open') ticker2['highPrice'] = ticker.pop('high') ticker2['lowPrice'] = ticker.pop('low') ticker2['volume'] = ticker.pop('baseVolume') ticker2['quoteVolume'] = ticker.pop('quoteVolume') ticker2['openTime'] = ticker.pop('datetime') ticker2['closeTime'] = ticker.pop('timestamp') ticker2['firstId'] = 'none' ticker2['lastId'] = 'none' ticker2['count'] = 'none' ticker = ticker2 return ticker
def print_hi(name): okex.g() # dates = ['01/02/1999', '01/03/1999', '01/04/1999'] # xs = [datetime.strptime(d, '%m/%d/%Y').date() for d in dates] # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint. # print(ccxt.binance().fetch_tickers('ETH/USDT')) exchange = ccxt.okex({ 'timeout': 30000, 'enableRateLimit': True, }) exchange.load_markets() kline = exchange.fetchOHLCV('ETH/USDT', timeframe='15m', since=1618880000000) print(kline) upperband, middleband, lowerband = talib.BBANDS(np.array( list(map(lambda k: k[4], kline))), timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) times = list( map(lambda k: maya.parse(exchange.iso8601(k[0])).datetime(), kline)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M')) ax.xaxis.set_major_locator(mdate.AutoDateLocator()) ax.plot(times, upperband) ax.plot(times, middleband) ax.plot(times, lowerband) plt.print_json()
def __init__(self, logs_file='./logs/logs.csv', db_name='okex', time_frame='1m', limit=100, instrument='ETH-USDT-SWAP', connection_settings=None, db_credentioals_file='./db_config/config.json', create_table=False): if connection_settings is None: with open(db_credentioals_file, 'r') as f: credentials = json.load(f) connection_settings = { 'database': credentials["database"], 'user': credentials["user"], 'password': credentials["password"], 'host': credentials["host"], 'port': credentials["port"] } self.connection_settings = connection_settings self.instrument = instrument self.exchange = ccxt.okex() self.connection = psycopg2.connect(**self.connection_settings) self.connection.autocommit = True self.cursor = self.connection.cursor() self.limit = limit self.time_frame = time_frame self.db_name = db_name self.logs_file = logs_file self.create_table = create_table logging.basicConfig(filename=self.logs_file, level=logging.INFO)
def get_prices(): # Should be enough for now exg = ccxt.okex() df_ticker = pd.DataFrame(retry_getter(exg.spot_get_instruments_ticker, 1)) df_ticker = df_ticker[df_ticker['instrument_id'].str.endswith('-USDT')] df_ticker['currency'] = df_ticker['instrument_id'].str.split('-').str[0] df_ticker.set_index('currency', inplace=True) df_ticker = df_ticker.append(pd.Series({'last': 1}, name='USDT')) df_ticker = df_ticker.append(pd.Series({'last': 1}, name='USD')) df_ticker['last'] = df_ticker['last'].astype('float') exg = ccxt.huobipro() df_ticker_hb = pd.DataFrame( retry_getter(exg.market_get_tickers, 1)['data']) df_ticker_hb = df_ticker_hb[df_ticker_hb['symbol'].str.endswith('usdt')] df_ticker_hb['currency'] = df_ticker_hb['symbol'].str[:-4].str.upper() df_ticker_hb['close'] = df_ticker_hb['close'].astype('float') df_ticker_hb.rename(columns={'close': 'last'}, inplace=True) df_ticker_hb = df_ticker_hb[['currency', 'last']].set_index('currency') exg = ccxt.binance() df_ticker_binance = pd.DataFrame(retry_getter(exg.publicGetTicker24hr, 1)) df_ticker_binance = df_ticker_binance[ df_ticker_binance['symbol'].str.endswith('USDT')] df_ticker_binance['currency'] = df_ticker_binance[ 'symbol'].str[:-4].str.upper() df_ticker_binance['last'] = df_ticker_binance['lastPrice'].astype('float') df_ticker_binance = df_ticker_binance[['currency', 'last']].set_index('currency') print(df_ticker_binance) df_ticker = pd.concat([df_ticker, df_ticker_hb, df_ticker_binance ]).groupby(level='currency').mean() return df_ticker[['last']]
def bar_base() -> Kline: exchane = ccxt.okex() kline_BTC = exchane.fetch_ohlcv('BTC/USDT', timeframe=time_change) df_BTC = pd.DataFrame(kline_BTC, dtype='float') df_BTC[0] = pd.to_datetime(df_BTC[0], unit='ms') # 转换为想要的时间 date = df_BTC[0].tolist() list_BTC_USDT = np.array(df_BTC[[1, 4, 3, 2]]).tolist() c = ( Kline() .add_xaxis(date) .add_yaxis('BTC', list_BTC_USDT) .set_global_opts( yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), xaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts(type_="inside")], title_opts=opts.TitleOpts(title="")) .dump_options() ) return c
def __init__(self): self.exo = ccxt.okex({ 'apiKey': settings['inactive']['apiKey'], 'secret': settings['inactive']['secret'] }) self.trade_symbol = settings['trade_symbol'] self.num_error = settings['inactive_exchange_num_error'] self.money_error = settings['inactive_exchange_money_error']
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 okex_ccxt_object(apiKey, apiSecret, param): ccxt_object = ccxt.okex({ 'timeout': 1000, # timeout时间短一点 'rateLimit': 10, 'enableRateLimit': False }) password = param.get('password') if password is not None: ccxt_object.password = password return CCXTObjectFactory._config_ccxt_object(ccxt_object, apiKey, apiSecret)
def __init__(self, key: str, secret: str, phrase: str): self.key = key self.secret = secret self.phrase = phrase self.cli = ccxt.okex( config={ "apiKey": key, "secret": secret, "password": phrase, "hostname": "okexcn.com" })
def connect(self, setting: dict): """ Start gateway connection. :param setting: :return: """ key = setting["API Key"] secret = setting["Secret Key"] self.gateway = ccxt.okex() self.gateway.apiKey = key self.gateway.secret = secret # 填充 交易对 self.__get_symbols()
def okexData(): okex = ccxt.okex() coindata = list(okex.fetch_tickers().values()) columns = ['ask', 'bid', 'close', 'high', 'low', 'last', 'symbol', 'average', 'baseVolume', 'timestamp'] df = pd.DataFrame(coindata) df = df[columns] df['exchange'] = 'okex' df['createtime'] = starttime df['baseCurrency'] = list(i.split('/')[0] for i in df['symbol']) df['quotCurrency'] = list(i.split('/')[1] for i in df['symbol']) engine = create_engine("mysql+pymysql://quziyou:0739#[email protected]:5389/coinData?charset=utf8") df.to_sql('coindata_tickers', con=engine, if_exists='append', index=False)
def get_exchange(contract_type='quarter'): if Application.config is None: return None if contract_type not in Application.exchange.keys(): e = ccxt.okex({ 'API_KEY': Application.config.get('OKEX', 'API_KEY'), 'SECRET': Application.config.get('OKEX', 'SECRET') }) e.load_markets() e.options['defaultContractType'] = contract_type Application.exchange[contract_type] = e return Application.exchange[contract_type]
def __init__(self, order_symbol, apikey, secret, num_buy, num_sell, order_spread, order_profit, order_amonut_buy, order_amonut_sell, exchange, password=None, order_type=None): self.order_symbol = order_symbol self.apiKey = apikey self.secret = secret self.order_type = order_type self.num_buy = num_buy self.num_sell = num_sell self.order_spread = order_spread self.order_profit = order_profit self.order_amonut_buy = order_amonut_buy self.order_amonut_sell = order_amonut_sell self.exchanges = exchange self.password = password # 初始化交易所 if self.exchanges == 'bitmex': if self.order_symbol == 'BTC/USD': self._symbol = 'XBTUSD' elif self.order_symbol == 'ETH/USD': self._symbol = 'ETHUSD' else: self._symbol = self.order_symbol self.exchange = ccxt.bitmex({"apiKey": self.apiKey, "secret": self.secret}) client = pymongo.MongoClient('localhost', port=27017) # 连接数据库 db = client['bitmex'] self.col = db[self._symbol] if self.exchanges == 'OKEX': if self.order_symbol == 'BTC/USD': self._symbol = 'BTC-USD-SWAP' elif self.order_symbol == 'ETH/USD': self._symbol = 'BTC-USD-SWAP' elif self.order_symbol == 'BTC/USDT': self._symbol = 'BTC-USDT-SWAP' elif self.order_symbol == 'ETH/USDT': self._symbol = 'BTC-USDT-SWAP' self.exchange = ccxt.okex({"apiKey": self.apiKey, "secret": self.secret, 'password': self.password}) client = pymongo.MongoClient('localhost', port=27017) # 连接数据库 db = client['OKEX'] self.col = db[self._symbol] if self.exchanges == 'Binance': self.exchange = ccxt.binance({"apiKey": self.apiKey, "secret": self.secret}) client = pymongo.MongoClient('localhost', port=27017) # 连接数据库 db = client['Binance'] self.col = db[self.order_symbol]
def get_ticker(): threading.Timer(1.0, get_ticker).start() exchange = ccxt.okex({ 'rateLimit': 3000, 'enableRateLimit': True, }) # tickers = exchange.fetch_ticker('BTC-USD') # print(tickers) # tickers = exchange.fetch_tickers(params={'type':'swap'}) # for i in tickers.keys(): # print(i) tick = exchange.fetch_ticker('BTC-USD-SWAP') print(tick['symbol'], tick['close'])
def get_okex_static(file): with open(file, 'a') as csvFile: csvwriter = csv.writer(csvFile) okex = ccxt.okex() for i in okex.fetch_markets(): if i['symbol'] in ['BTC/USDT', 'ETH/USDT', 'BCH/USDT'] and i['info']['symbol']\ in ['btc_usdt', 'eth_usdt', 'bch_usdt']: uid = i['symbol'].replace('/', '_') + '-okex' csvwriter.writerow([ uid, 'Okex', i['id'], i['info']['quoteIncrement'], '1', i['limits']['amount']['min'], i['limits']['amount']['max'], i['limits']['price']['min'], i['limits']['price']['max'], i['precision']['amount'], i['precision']['price'], i['taker'] * 10000, i['maker'] * 10000, 0, 0, 'cryptocurrency' ])
def get_okex_future_orders(secret): exg = ccxt.okex(secret) df_mkt = pd.DataFrame(exg.load_markets()).T future_ids = df_mkt[df_mkt['futures']]['id'] df_order_list = [] for inst_id in future_ids: order_data = retry_getter( lambda: exg.futures_get_orders_instrument_id({ 'instrument_id': inst_id, 'state': 7 }), 2) df_order = pd.DataFrame(order_data['order_info']) df_order_list.append(df_order) order_data = retry_getter( lambda: exg.futures_get_orders_instrument_id({ 'instrument_id': inst_id, 'state': 6 }), 2) df_order = pd.DataFrame(order_data['order_info']) df_order_list.append(df_order) df_order = pd.concat(df_order_list) return df_order
def okexAgg(symbols): result = [] try: okex = ccxt.okex({ 'apiKey': 'apiKey', 'secret': 'secret', 'options': { 'adjustForTimeDifference': True } }) totalBalance = okex.fetch_balance()["free"] exchangeSymbols = okex.symbols checkSymbols = list(np.intersect1d(exchangeSymbols, symbols)) allData = okex.fetch_tickers(checkSymbols) ethPrice = okex.fetch_ticker("ETH/USDT")["last"] btcPrice = okex.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(["okex", s, coinBalance, ask, bid, volume]) except: print("Okex couldn`t get " + s) continue except Exception as e: print(str(e)[:150]) return (result)
def car_base() -> Kline: exchane = ccxt.okex() kline_ETC = exchane.fetch_ohlcv('ETC/USDT', timeframe=time_change) kline_XRP = exchane.fetch_ohlcv('XRP/USDT', timeframe=time_change) kline_EOS = exchane.fetch_ohlcv('EOS/USDT', timeframe=time_change) kline_TRX = exchane.fetch_ohlcv('TRX/USDT', timeframe=time_change) df_ETC = pd.DataFrame(kline_ETC, dtype='float') df_XRP = pd.DataFrame(kline_XRP, dtype='float') df_EOS = pd.DataFrame(kline_EOS, dtype='float') df_TRX = pd.DataFrame(kline_TRX, dtype='float') df_ETC[0] = pd.to_datetime(df_ETC[0], unit='ms') df_XRP[0] = pd.to_datetime(df_XRP[0], unit='ms') df_EOS[0] = pd.to_datetime(df_EOS[0], unit='ms') df_TRX[0] = pd.to_datetime(df_TRX[0], unit='ms') date = df_ETC[0].tolist() list_ETC_USDT = np.array(df_ETC[[1, 4, 3, 2]]).tolist() list_XRP_USDT = np.array(df_XRP[[1, 4, 3, 2]]).tolist() list_EOS_USDT = np.array(df_EOS[[1, 4, 3, 2]]).tolist() list_TRX_USDT = np.array(df_TRX[[1, 4, 3, 2]]).tolist() c = (Kline().add_xaxis(date).add_yaxis('ETC', list_ETC_USDT).add_yaxis( 'XRP', list_XRP_USDT).add_yaxis('EOS', list_EOS_USDT).add_yaxis( 'TRX', list_TRX_USDT).set_global_opts( yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), xaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts(type_="inside")], )) return c
def aar_base() -> Kline: exchane = ccxt.okex() kline_LTC = exchane.fetch_ohlcv('LTC/USDT', timeframe=time_change) kline_ETH = exchane.fetch_ohlcv('ETH/USDT', timeframe=time_change) kline_BCH = exchane.fetch_ohlcv('BCH/USDT', timeframe=time_change) kline_BSV = exchane.fetch_ohlcv('BSV/USDT', timeframe=time_change) df_LTC = pd.DataFrame(kline_LTC, dtype='float') df_ETH = pd.DataFrame(kline_ETH, dtype='float') df_BCH = pd.DataFrame(kline_BCH, dtype='float') df_BSV = pd.DataFrame(kline_BSV, dtype='float') df_LTC[0] = pd.to_datetime(df_LTC[0], unit='ms') df_ETH[0] = pd.to_datetime(df_ETH[0], unit='ms') df_BCH[0] = pd.to_datetime(df_BCH[0], unit='ms') df_BSV[0] = pd.to_datetime(df_BSV[0], unit='ms') date = df_LTC[0].tolist() list_lTC_USDT = np.array(df_LTC[[1, 4, 3, 2]]).tolist() list_ETH_USDT = np.array(df_ETH[[1, 4, 3, 2]]).tolist() list_BCH_USDT = np.array(df_BCH[[1, 4, 3, 2]]).tolist() list_BSV_USDT = np.array(df_BSV[[1, 4, 3, 2]]).tolist() c = (Kline().add_xaxis(date).add_yaxis('LTC', list_lTC_USDT).add_yaxis( 'ETH', list_ETH_USDT).add_yaxis('BCH', list_BCH_USDT).add_yaxis( 'BSV', list_BSV_USDT).set_global_opts( yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), xaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts(type_="inside")], )) return c
def _load_okex_trades_data(symbol): okex = ccxt.okex({'verbose': True}) markets = okex.load_markets() trades = okex.fetch_trades(symbol) print(trades) l = len(trades) L = list(range(l)) trades_bak = [] i = 0 for i in L: trades_1 = trades[i] trades2 = {} trades2['a'] = trades_1.pop('id') trades2['p'] = trades_1.pop('price') trades2['q'] = trades_1.pop('amount') trades2['f'] = 'none' trades2['l'] = 'none' trades2['T'] = trades_1.pop('timestamp') trades2['m'] = 'none' trades2['M'] = 'none' trades_bak.append(trades2) trades = trades2 return trades
# save result = df[[atr, st, stx]].copy() # Remove df.drop([atr, st, stx], inplace=True, axis=1) result.fillna(0, inplace=True) return result[atr], result[st], result[stx] exchange = ccxt.okex({ 'proxies': proxies if enable_proxies else None, 'apiKey': apiKey, 'secret': secret, 'timeout': 20000, 'enableRateLimit': True }) # 两天前 since = beforeHours2Timestamp(hours) for currency in base: info = exchange.fetch_balance() base_pos = info[currency] quote_pos = info[quote] # 货币组合 symbol = '{}/{}'.format(currency, quote)
# -*- coding: utf-8 -*- import os import sys import time # ------------------------------------------------------------------------------ root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root) # ------------------------------------------------------------------------------ import ccxt # noqa: E402 # ------------------------------------------------------------------------------ exchange = ccxt.okex() exchange.load_markets() for symbol in exchange.markets: market = exchange.markets[symbol] if market['future']: print('----------------------------------------------------') print(symbol, exchange.fetchTicker(symbol)) time.sleep(exchange.rateLimit / 1000)
from django.core.management.base import BaseCommand, CommandError from contract.models import Tradepair import ccxt import json import time import requests config = json.load(open('config_funding.json')) binance_future = ccxt.binance(config["binance_future"]) binance_future.load_markets() binance_spot = ccxt.binance(config["binance_spot"]) binance_spot.load_markets() okex_future = ccxt.okex(config["okex_future"]) okex_spot = ccxt.okex(config["okex_spot"]) okex_future.load_markets() okex_spot.load_markets() huobi_spot = ccxt.huobipro() huobi_spot.load_markets() swapusd = [] swapusdt = [] swap = [] for symbol in okex_future.markets: if "USD-SWAP" in symbol: swapusd.append(symbol) if "USDT-SWAP" in symbol: swapusdt.append(symbol)
def __init__(self, config): if config["exchange_market"] == "okex": logging.info("Creating OKEx emulate bot...") self.exchange = ccxt.okex({ 'apiKey': config["api_access"]["api_key"], 'secret': config["api_access"]["secret"], 'password': config["api_access"]["password"], 'enableRateLimit': True, 'options': { 'defaultType': config["exchange_type"], }, }) else: logging.info("Creating Binance emulate bot...") self.exchange = ccxt.binance({ 'apiKey': config["api_access"]["api_key"], 'secret': config["api_access"]["secret"], 'enableRateLimit': True, 'options': { 'defaultType': config["exchange_type"], }, }) # Load markets markets = self.exchange.load_markets() # Create runtime directory if not os.path.isdir(config['runtime_dir']): os.mkdir(config['runtime_dir']) # Runtime information path self.__info_path = f'{config["runtime_dir"]}info.json' # Runtime open order path self.__orders_path = f'{config["runtime_dir"]}orders.json' # Runtime setting path self.__setting_path = f'{config["runtime_dir"]}setting.json' if not os.path.exists(self.__info_path): # Create info file with open(self.__info_path, 'w') as outfile: info = {} json.dump(info, outfile) if not os.path.exists(self.__orders_path): # Create order record file with open(self.__orders_path, 'w') as outfile: order = {} json.dump(order, outfile) # Order manager self.om = OrderManager(self.__orders_path) # Track complete order history self.__order_history = [] # Order ID Issuer self.__order_id = 0 logging.info("Emulate bot created.")
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.okex({ 'proxies': { 'http': 'http://127.0.0.1:1080', # no auth 'https': 'https://127.0.0.1:1080', # with auth }, 'apiKey': '78e83f11-0fc6-41ba-bb60-8c9042dae10f', 'secret': '9F9E3F62F577C6C34FD73540044C4B15', 'enableRateLimit': True, }) exchange.load_markets() tickerFile = open("ticker.txt", "w") for symbol in exchange.markets: market = exchange.markets[symbol] if market['future']: print('----------------------------------------------------') data = exchange.fetchTicker(symbol) print(symbol, data) tickerFile.write( '\r\n----------------------------------------------------\r\n')
def _load_okex_orderbook_data(symbol): okex = ccxt.okex({'verbose': True}) markets = okex.load_markets() orderbook = okex.fetch_order_book(symbol) return orderbook
def _load_okex_ohlcv_data(symbol): okex = ccxt.okex({'verbose': True}) markets = okex.load_markets() ohlcv = okex.fetch_ohlcv(symbol) return ohlcv
else: file = open(exchange + '/' + symbol.replace('/', '').lower() + '.csv', 'a+', newline='') write = csv.writer(file, dialect='excel') for i in range(len(data)): write.writerow(data.iloc[i]) file.close() time.sleep(1) if __name__ == '__main__': obj_list = [ ccxt.okex(), ccxt.huobipro(), ccxt.binance(), ccxt.bitmax(), ccxt.fcoin(), ccxt.upbit() ] file = open('config.txt', 'r') config = json.loads(file.read()) file.close() mkdir(config['name_list']) time_info = get_time_info(config['name_list'], config['symbol_list']) info_queue = Queue() for obj, name in zip(obj_list, config['name_list']): crawl = CrawlInfo(obj, info_queue, name, config['symbol_list']) crawl.start()
# -*- coding: utf-8 -*- import os import sys import time # ------------------------------------------------------------------------------ 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.okex() exchange.load_markets() for symbol in exchange.markets: market = exchange.markets[symbol] if market['future']: print('----------------------------------------------------') print(symbol, exchange.fetchTicker(symbol)) time.sleep(exchange.rateLimit / 1000)