GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — ccxt/python/test/test.py at master · electic/ccxt Expand file tree/ Copy pathtest.pyMore file actions 403 lines (291 loc) · 12.2 KB / Copy pathtest.pyFile metadata and controls403 lines (291 loc) · 12.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 # -*- coding: utf-8 -*- import argparse import json # import logging import os import sys import time # noqa: F401 from os import _exit from traceback import format_tb # ------------------------------------------------------------------------------ # logging.basicConfig(level=logging.INFO) # ------------------------------------------------------------------------------ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(root) # ------------------------------------------------------------------------------ import ccxt # noqa: E402 # ------------------------------------------------------------------------------ class Argv(object): verbose = False nonce = None exchange = None symbol = None pass argv = Argv() parser = argparse.ArgumentParser() parser.add_argument('--verbose', action='store_true', help='enable verbose output') parser.add_argument('--nonce', type=int, help='integer') parser.add_argument('exchange', type=str, help='exchange id in lowercase', nargs='?') parser.add_argument('symbol', type=str, help='symbol in uppercase', nargs='?') parser.parse_args(namespace=argv) exchanges = {} # ------------------------------------------------------------------------------ path = os.path.dirname(ccxt.__file__) if 'site-packages' in os.path.dirname(ccxt.__file__): raise Exception('\n\nYou are running test_async.py/test.py against a globally-installed version of the library!\nIt was previously installed into your site-packages folder by pip or pip3.\n\nTo ensure testing against the local folder uninstall it first by running the following commands:\npip uninstall ccxt\npip3 uninstall ccxt\n\n') # ------------------------------------------------------------------------------ # string coloring functions def style(s, style): return str(s) # style + str (s) + '\033[0m' def green(s): return style(s, '\033[92m') def blue(s): return style(s, '\033[94m') def yellow(s): return style(s, '\033[93m') def red(s): return style(s, '\033[91m') def pink(s): return style(s, '\033[95m') def bold(s): return style(s, '\033[1m') def underline(s): return style(s, '\033[4m') # print a colored string def dump(*args): print(' '.join([str(arg) for arg in args])) # print an error string def dump_error(*args): string = ' '.join([str(arg) for arg in args]) print(string) sys.stderr.write(string + "\n") # ------------------------------------------------------------------------------ def handle_all_unhandled_exceptions(type, value, traceback): dump_error(yellow(type), yellow(value), '\n\n' + yellow('\n'.join(format_tb(traceback)))) _exit(1) # unrecoverable crash sys.excepthook = handle_all_unhandled_exceptions # ------------------------------------------------------------------------------ def test_order_book(exchange, symbol): if exchange.has['fetchOrderBook']: delay = int(exchange.rateLimit / 1000) time.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching order book...') orderbook = exchange.fetch_order_book(symbol) dump( green(exchange.id), green(symbol), 'order book', orderbook['datetime'], 'bid: ' + str(orderbook['bids'][0][0] if len(orderbook['bids']) else 'N/A'), 'bidVolume: ' + str(orderbook['bids'][0][1] if len(orderbook['bids']) else 'N/A'), 'ask: ' + str(orderbook['asks'][0][0] if len(orderbook['asks']) else 'N/A'), 'askVolume: ' + str(orderbook['asks'][0][1] if len(orderbook['asks']) else 'N/A')) else: dump(yellow(exchange.id), 'fetch_order_book() supported') # ------------------------------------------------------------------------------ def test_ohlcv(exchange, symbol): if exchange.has['fetchOHLCV']: delay = int(exchange.rateLimit / 1000) time.sleep(delay) ohlcvs = exchange.fetch_ohlcv(symbol) dump(green(exchange.id), 'fetched', green(len(ohlcvs)), 'OHLCVs') else: dump(yellow(exchange.id), 'fetching OHLCV not supported') # ------------------------------------------------------------------------------ def test_tickers(exchange, symbol): if exchange.has['fetchTickers']: delay = int(exchange.rateLimit / 1000) time.sleep(delay) tickers = None try: # dump(green(exchange.id), 'fetching all tickers at once...') tickers = exchange.fetch_tickers() dump(green(exchange.id), 'fetched all', green(len(list(tickers.keys()))), 'tickers') except Exception as e: dump(green(exchange.id), 'failed to fetch all tickers, fetching multiple tickers at once...') tickers = exchange.fetch_tickers([symbol]) dump(green(exchange.id), 'fetched', green(len(list(tickers.keys()))), 'tickers') # ------------------------------------------------------------------------------ def get_active_symbols(exchange): return [symbol for symbol in exchange.symbols if is_active_symbol(exchange, symbol)] def is_active_symbol(exchange, symbol): return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active'])) # ------------------------------------------------------------------------------ def test_ticker(exchange, symbol): if exchange.has['fetchTicker']: delay = int(exchange.rateLimit / 1000) time.sleep(delay) ticker = exchange.fetch_ticker(symbol) dump( green(exchange.id), green(symbol), 'ticker', ticker['datetime'], 'high: ' + str(ticker['high']), 'low: ' + str(ticker['low']), 'bid: ' + str(ticker['bid']), 'ask: ' + str(ticker['ask']), 'volume: ' + str(ticker['quoteVolume'])) else: dump(green(exchange.id), green(symbol), 'fetch_ticker() not supported') # ------------------------------------------------------------------------------ def test_trades(exchange, symbol): if exchange.has['fetchTrades']: delay = int(exchange.rateLimit / 1000) time.sleep(delay) # dump(green(exchange.id), green(symbol), 'fetching trades...') trades = exchange.fetch_trades(symbol) dump(green(exchange.id), green(symbol), 'fetched', green(len(list(trades))), 'trades') else: dump(green(exchange.id), green(symbol), 'fetch_trades() not supported') # ------------------------------------------------------------------------------ def test_symbol(exchange, symbol): dump(green('SYMBOL: ' + symbol)) test_ticker(exchange, symbol) if exchange.id == 'coinmarketcap': response = exchange.fetchGlobal() dump(green(response)) else: test_order_book(exchange, symbol) test_trades(exchange, symbol) test_tickers(exchange, symbol) test_ohlcv(exchange, symbol) # ------------------------------------------------------------------------------ def load_exchange(exchange): exchange.load_markets() def test_exchange(exchange): dump(green('EXCHANGE: ' + exchange.id)) # delay = 2 keys = list(exchange.markets.keys()) # .......................................................................... # public API symbol = keys[0] symbols = [ 'BTC/USD', 'BTC/USDT', 'BTC/CNY', 'BTC/EUR', 'BTC/ETH', 'ETH/BTC', 'BTC/JPY', 'LTC/BTC', 'USD/SLL', ] for s in symbols: if s in keys: symbol = s break if symbol.find('.d') < 0: test_symbol(exchange, symbol) # .......................................................................... # private API if (not hasattr(exchange, 'apiKey') or (len(exchange.apiKey) < 1)): return # move to testnet/sandbox if possible before accessing the balance if possible # if 'test' in exchange.urls: # exchange.urls['api'] = exchange.urls['test'] exchange.fetch_balance() dump(green(exchange.id), 'fetched balance') time.sleep(exchange.rateLimit / 1000) if exchange.has['fetchOrders']: try: orders = exchange.fetch_orders(symbol) dump(green(exchange.id), 'fetched', green(str(len(orders))), 'orders') except (ccxt.ExchangeError, ccxt.NotSupported) as e: dump_error(yellow('[' + type(e).__name__ + ']'), e.args) # except ccxt.NotSupported as e: # dump(yellow(type(e).__name__), e.args) # time.sleep(delay) # amount = 1 # price = 0.0161 # marketBuy = exchange.create_market_buy_order(symbol, amount) # print(marketBuy) # time.sleep(delay) # marketSell = exchange.create_market_sell_order(symbol, amount) # print(marketSell) # time.sleep(delay) # limitBuy = exchange.create_limit_buy_order(symbol, amount, price) # print(limitBuy) # time.sleep(delay) # limitSell = exchange.create_limit_sell_order(symbol, amount, price) # print(limitSell) # time.sleep(delay) # ------------------------------------------------------------------------------ def try_all_proxies(exchange, proxies=['']): current_proxy = 0 max_retries = len(proxies) # a special case for ccex if exchange.id == 'ccex' and max_retries > 1: current_proxy = 1 for num_retries in range(0, max_retries): try: exchange.proxy = proxies[current_proxy] dump(green(exchange.id), 'using proxy', '`' + exchange.proxy + '`') current_proxy = (current_proxy + 1) % len(proxies) load_exchange(exchange) test_exchange(exchange) except ccxt.RequestTimeout as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e)[0:200]) except ccxt.NotSupported as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e.args)[0:200]) except ccxt.DDoSProtection as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e.args)[0:200]) except ccxt.ExchangeNotAvailable as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e.args)[0:200]) except ccxt.AuthenticationError as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e)[0:200]) except ccxt.ExchangeError as e: dump_error(yellow('[' + type(e).__name__ + ']'), str(e.args)[0:200]) else: # no exception return True # exception return False # ------------------------------------------------------------------------------ proxies = [ '', 'https://cors-anywhere.herokuapp.com/', # 'https://crossorigin.me/', ] # prefer local testing keys to global keys keys_folder = os.path.dirname(root) keys_global = os.path.join(keys_folder, 'keys.json') keys_local = os.path.join(keys_folder, 'keys.local.json') keys_file = keys_local if os.path.exists(keys_local) else keys_global # load the api keys from config with open(keys_file) as file: config = json.load(file) # instantiate all exchanges for id in ccxt.exchanges: if id == 'theocean' or id == 'theocean1': continue exchange = getattr(ccxt, id) exchange_config = {'verbose': argv.verbose} if sys.version_info[0] < 3: exchange_config.update({'enableRateLimit': True}) if id in config: exchange_config.update(config[id]) exchanges[id] = exchange(exchange_config) # ------------------------------------------------------------------------------ def main(): if argv.exchange: if argv.exchange != 'theocean' and argv.exchange != 'theocean1': exchange = exchanges[argv.exchange] symbol = argv.symbol if hasattr(exchange, 'skip') and exchange.skip: dump(green(exchange.id), 'skipped') else: if symbol: load_exchange(exchange) test_symbol(exchange, symbol) else: try_all_proxies(exchange, proxies) else: for exchange in sorted(exchanges.values(), key=lambda x: x.id): if hasattr(exchange, 'skip') and exchange.skip: dump(green(exchange.id), 'skipped') else: try_all_proxies(exchange, proxies) # ------------------------------------------------------------------------------ if __name__ == '__main__': main() |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |