Skip to content

Commit

Permalink
ccxt#106 removed whitespace from Python examples
Browse files Browse the repository at this point in the history
  • Loading branch information
kroitor committed Aug 13, 2017
1 parent a593ae0 commit cc1628d
Show file tree
Hide file tree
Showing 6 changed files with 207 additions and 216 deletions.
4 changes: 3 additions & 1 deletion examples/py/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# CCXT Python Examples

To run Python examples from any folder type in console:
To run Python examples from any folder, type in console:

```shell
python path/to/example.py # substitute for actual filename here
```

The examples are compatible with Python 2 and 3.
110 changes: 54 additions & 56 deletions examples/py/arbitrage-pairs.py
Original file line number Diff line number Diff line change
@@ -1,107 +1,105 @@
# coding=utf-8

def style (s, style): return style + 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')
# -*- 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)
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)

import ccxt # noqa: E402

import ccxt
def style(s, style): return style + 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')

def dump (*args):
print (' '.join ([str (arg) for arg in args]))
def dump(*args):
print(' '.join([str(arg) for arg in args]))

def print_exchanges ():
dump ('Supported exchanges:', ', '.join (ccxt.exchanges))
def print_exchanges():
dump('Supported exchanges:', ', '.join(ccxt.exchanges))

def print_usage ():
dump ("Usage: python " + sys.argv[0], green ('id1'), yellow ('id2'), blue ('id3'), '...')
def print_usage():
dump("Usage: python " + sys.argv[0], green('id1'), yellow('id2'), blue('id3'), '...')

proxies = [
'', # no proxy by default
'', # no proxy by default
'https://crossorigin.me/',
'https://cors-anywhere.herokuapp.com/',
];
]

if len (sys.argv) > 2:
ids = list (sys.argv[1:])
if len(sys.argv) > 2:
ids = list(sys.argv[1:])
exchanges = {}
dump (ids)
dump (yellow (' '.join (ids)))
for id in ids: # load all markets from all exchange exchanges
dump(ids)
dump(yellow(' '.join(ids)))
for id in ids: # load all markets from all exchange exchanges

# instantiate the exchange by id
exchange = getattr (ccxt, id) ()
exchange = getattr(ccxt, id)()

# save it in a dictionary under its id for future use
exchanges[id] = exchange

# load all markets from the exchange
markets = exchange.load_markets ()
markets = exchange.load_markets()

# basic round-robin proxy scheduler
currentProxy = -1
maxRetries = len (proxies)
for numRetries in range (0, maxRetries):
maxRetries = len(proxies)

for numRetries in range(0, maxRetries):

# try proxies in round-robin fashion
currentProxy = (currentProxy + 1) % len (proxies)
currentProxy = (currentProxy + 1) % len(proxies)

try: # try to load exchange markets using current proxy
try: # try to load exchange markets using current proxy

exchange.proxy = proxies[currentProxy]
exchange.load_markets ()
exchange.load_markets()

except ccxt.DDoSProtection as e:
dump (yellow (type (e).__name__), e.args)
dump(yellow(type(e).__name__), e.args)
except ccxt.RequestTimeout as e:
dump (yellow (type (e).__name__), e.args)
dump(yellow(type(e).__name__), e.args)
except ccxt.AuthenticationError as e:
dump (yellow (type (e).__name__), e.args)
dump(yellow(type(e).__name__), e.args)
except ccxt.ExchangeNotAvailable as e:
dump (yellow (type (e).__name__), e.args)
dump(yellow(type(e).__name__), e.args)
except ccxt.ExchangeError as e:
dump (yellow (type (e).__name__), e.args)
dump(yellow(type(e).__name__), e.args)
except ccxt.NetworkError as e:
dump (yellow (type (e).__name__), e.args)
except Exception as e: # reraise all other exceptions
raise
dump(yellow(type(e).__name__), e.args)
except Exception as e: # reraise all other exceptions
raise

dump (green (id), 'loaded', green (str (len (exchange.symbols))), 'markets')
dump(green(id), 'loaded', green(str(len(exchange.symbols))), 'markets')

dump (green ('Loaded all markets'))
dump(green('Loaded all markets'))

allSymbols = [symbol for id in ids for symbol in exchanges[id].symbols]

# get all unique symbols
uniqueSymbols = list (set (allSymbols))
uniqueSymbols = list(set(allSymbols))

# filter out symbols that are not present on at least two exchanges
arbitrableSymbols = sorted ([symbol for symbol in uniqueSymbols if allSymbols.count (symbol) > 1])
arbitrableSymbols = sorted([symbol for symbol in uniqueSymbols if allSymbols.count(symbol) > 1])

# print a table of arbitrable symbols
table = []
dump (green (' symbol | ' + ''.join ([' {:<15} | '.format (id) for id in ids])))
dump (green (''.join (['-----------------+-' for x in range (0, len (ids) + 1)])))
dump(green(' symbol | ' + ''.join([' {:<15} | '.format(id) for id in ids])))
dump(green(''.join(['-----------------+-' for x in range(0, len(ids) + 1)])))

for symbol in arbitrableSymbols:
string = ' {:<15} | '.format (symbol)
row = { }
string = ' {:<15} | '.format(symbol)
row = {}
for id in ids:
# if a symbol is present on a exchange print that exchange's id in the row
string += ' {:<15} | '.format (id if symbol in exchanges[id].symbols else '')
dump (string)
string += ' {:<15} | '.format(id if symbol in exchanges[id].symbols else '')
dump(string)

else:

print_usage ()
print_usage()
74 changes: 36 additions & 38 deletions examples/py/balances.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,69 @@
# coding=utf-8

def style (s, style): return style + 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')
# -*- 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)
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)

import ccxt # noqa: E402

import ccxt
def style(s, style): return style + 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')

def dump(*args):
print(' '.join([str(arg) for arg in args]))

def dump (*args):
print (' '.join ([str (arg) for arg in args]))

# instantiate exchanges

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

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

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

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

try:

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

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

# fetch another one
hitbtcBalance = hitbtc.fetch_balance ()
hitbtcBalance = hitbtc.fetch_balance()

# output the result
dump (green (hitbtc.name), 'balance', hitbtcBalance)
dump(green(hitbtc.name), 'balance', hitbtcBalance)

# ... and another one
quadrigacxBalance = quadrigacx.fetch_balance ()
quadrigacxBalance = quadrigacx.fetch_balance()

# output the result
dump (green (quadrigacx.name), 'balance', quadrigacxBalance)
dump(green(quadrigacx.name), 'balance', quadrigacxBalance)

except ccxt.DDoSProtection as e:
print (type (e).__name__, e.args, 'DDoS Protection (ignoring)')
except ccxt.TimeoutError as e:
print (type (e).__name__, e.args, 'Request Timeout (ignoring)')
print(type(e).__name__, e.args, 'DDoS Protection (ignoring)')
except ccxt.RequestTimeout as e:
print(type(e).__name__, e.args, 'Request Timeout (ignoring)')
except ccxt.ExchangeNotAvailable as e:
print (type (e).__name__, e.args, 'Exchange Not Available due to downtime or maintenance (ignoring)')
print(type(e).__name__, e.args, 'Exchange Not Available due to downtime or maintenance (ignoring)')
except ccxt.AuthenticationError as e:
print (type (e).__name__, e.args, 'Authentication Error (missing API keys, ignoring)')
print(type(e).__name__, e.args, 'Authentication Error (missing API keys, ignoring)')
45 changes: 22 additions & 23 deletions examples/py/exchanges.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
# coding=utf-8

def style (s, style): return 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')
# -*- 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)
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)

import ccxt # noqa: E402

import ccxt
def style(s, style): return style + 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')

exchanges = {}

for id in ccxt.exchanges:
exchange = getattr (ccxt, id)
exchanges[id] = exchange ()
exchange = getattr(ccxt, id)
exchanges[id] = exchange()

def log (*args):
print (' '.join ([str (arg) for arg in args]))
def log(*args):
print(' '.join([str(arg) for arg in args]))

log ('The ccxt library supports', green (len (ccxt.exchanges)), 'exchanges:')
log('The ccxt library supports', green(len(ccxt.exchanges)), 'exchanges:')

# output a table of all exchanges
log (pink ('{:<15} {:<15} {:<15}'.format ('id', 'name', 'URL')))
tuples = list (ccxt.Exchange.keysort (exchanges).items ())
log(pink('{:<15} {:<15} {:<15}'.format('id', 'name', 'URL')))
tuples = list(ccxt.Exchange.keysort(exchanges).items())
for (id, params) in tuples:
exchange = exchanges[id]
website = exchange.urls['www'][0] if type (exchange.urls['www']) is list else exchange.urls['www']
log ('{:<15} {:<15} {:<15}'.format (exchange.id, exchange.name, website))

website = exchange.urls['www'][0] if type(exchange.urls['www']) is list else exchange.urls['www']
log('{:<15} {:<15} {:<15}'.format(exchange.id, exchange.name, website))
Loading

0 comments on commit cc1628d

Please sign in to comment.