import exchanges
import math

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    '''
    Python 2 implementation of Python 3.5 math.isclose()
    https://hg.python.org/cpython/file/tip/Modules/mathmodule.c#l1993
    '''
    # sanity check on the inputs
    if rel_tol < 0 or abs_tol < 0:
        raise ValueError("tolerances must be non-negative")
    # short circuit exact equality -- needed to catch two infinities of
    # the same sign. And perhaps speeds things up a bit sometimes.
    if a == b:
        return True

    # This catches the case of two infinities of opposite sign, or
    # one infinity and one finite number. Two infinities of opposite
    # sign would otherwise have an infinite relative tolerance.
    # Two infinities of the same sign are caught by the equality check
    # above.
    if math.isinf(a) or math.isinf(b):
        return False

    # now do the regular computation
    # this is essentially the "weak" test from the Boost library
    diff = math.fabs(b - a)
    result = (((diff <= math.fabs(rel_tol * b)) or
               (diff <= math.fabs(rel_tol * a))) or
              (diff <= abs_tol))
    return result

e = exchanges.get_exchange('gatecoin')

orders = e.get_live_orders()

print("%s live orders" % len(orders))

ob = {}
underlying = {}

for order in orders:
    print('%s: %s %s %s at %s' % (order['clOrderId'], 'Buy' if order['side'] == 0 else 'Sell', order['initialQuantity'], order['code'], order['price']))
    if order['side'] == 0:
        if order['code'] in ob.keys():
            ob[order['code']]['bid'] = order['price']
        else:
            ob[order['code']] = {'bid': order['price'], 'ask' : 0}
    else:
        if order['code'] in ob.keys():
            ob[order['code']]['ask'] = order['price']
        else:
            ob[order['code']] = {'bid': 0, 'ask' : order['price']}

# markets
print("Current markets")
for ul in ob.keys():
    depth = e.get_depth(ul)
    print("%s: %s" % (ul, depth))
    if ob[ul]['bid'] != 0 and isclose(ob[ul]['bid'],depth[0]):
        print("Best bid for %s" % ul)
    if ob[ul]['ask'] !=0 and isclose(ob[ul]['ask'],depth[1]):
        print("Best offer for %s" % ul)


