# get the levels 5% 10% 20% 50% 100% above the lowest ask for every exchange
import requests




api_url_coinbase_usd = "https://api.exchange.coinbase.com/products/BTC-USD/book?level=2"
api_url_coinbase_usdt = "https://api.exchange.coinbase.com/products/BTC-USDT/book?level=2"
api_url_coinbase_eur = "https://api.exchange.coinbase.com/products/BTC-EUR/book?level=2"
api_url_coinbase_gbp = "https://api.exchange.coinbase.com/products/BTC-GBP/book?level=2"

api_url_bitfinex_usd = "https://api.bitfinex.com/v2/book/tBTCUSD/P2?len=100"
api_url_bitfinex_usdt = "https://api.bitfinex.com/v2/book/tBTCUST/P2?len=100"
api_url_bitfinex_eur = "https://api.bitfinex.com/v2/book/tBTCEUR/P2?len=100"
api_url_bitfinex_gbp = "https://api.bitfinex.com/v2/book/tBTCGBP/P2?len=100"

api_url_bitflyer_jpy = "https://api.bitflyer.com/v1/getboard?product_code=BTC_JPY"

api_url_gemini_usd = "https://api.gemini.com/v1/book/btcusd?limit_bids=0&limit_asks=0"

api_file_binance_usdt = "./orderbook.txt"



# Make the API request

response_coinbase_usd = requests.get(api_url_coinbase_usd)
response_coinbase_usdt = requests.get(api_url_coinbase_usdt)
response_coinbase_eur = requests.get(api_url_coinbase_eur)
response_coinbase_gbp = requests.get(api_url_coinbase_gbp)

response_bitfinex_usd = requests.get(api_url_bitfinex_usd)
response_bitfinex_usdt = requests.get(api_url_bitfinex_usdt)
response_bitfinex_eur = requests.get(api_url_bitfinex_eur)
response_bitfinex_gbp = requests.get(api_url_bitfinex_gbp)

response_bitflyer_jpy = requests.get(api_url_bitflyer_jpy)

response_gemini_usd = requests.get(api_url_gemini_usd)


# Parse the JSON response
data_coinbase_usd = response_coinbase_usd.json()
data_coinbase_usdt = response_coinbase_usdt.json()
data_coinbase_eur = response_coinbase_eur.json()
data_coinbase_gbp = response_coinbase_gbp.json()

data_bitfinex_usd = response_bitfinex_usd.json()
data_bitfinex_usdt = response_bitfinex_usdt.json()
data_bitfinex_eur = response_bitfinex_eur.json()
data_bitfinex_gbp = response_bitfinex_gbp.json()

data_bitflyer_jpy = response_bitflyer_jpy.json()

data_gemini_usd = response_gemini_usd.json()


# Filter and print bids greater than x% above the lowest ask


#safe the orderbook levels in a list
coinbase_usd = []
coinbase_eur = []
coinbase_usdt = []
bitfinex_usd = []
bitfinex_usdt = []
bitfinex_eur = []
bitflyer_jpy = []
gemini_usd = []
binance_usdt = []

#same for bids
coinbase_bids_usd = []
coinbase_bids_eur = []
coinbase_bids_usdt = []
bitfinex_bids_usd = []
bitfinex_bids_usdt = []
bitfinex_bids_eur = []
bitflyer_bids_jpy = []
gemini_bids_usd = []
binance_bids_usdt = []



def get_levels_coinbase(data, percentage, currency):
    #get bids and asks
    asks = data["asks"]
    orders = []
    price = round(float(asks[0][0])*(1 + percentage/100))

    for ask in asks:
        if(float(ask[0]) < price):
            orders.append(ask)

    total_amount = round(sum(float(order[1]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Ask Amount: {total_amount} at {price}")
    #append the total amount to the list
    if(currency == "USD"):
        coinbase_usd.append(total_amount)
    elif(currency == "EUR"):
        coinbase_eur.append(total_amount)
    elif(currency == "USDT"):
        coinbase_usdt.append(total_amount)

    bids = data["bids"]
    orders = []
    price = round(float(bids[0][0])*(1 - percentage/100))
    for bid in bids:
        if(float(bid[0]) > price):
            orders.append(bid)

    total_amount = round(sum(float(order[1]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Bid Amount: {total_amount} at {price}")
    #append the total amount to the list
    if(currency == "USD"):
        coinbase_bids_usd.append(total_amount)
    elif(currency == "EUR"):
        coinbase_bids_eur.append(total_amount)
    elif(currency == "USDT"):
        coinbase_bids_usdt.append(total_amount)



def get_levels_bitfinex(data, percentage, currency):
    asks = data
    orders = []
    price = round(float(asks[0][0])*(1 + percentage/100))

    for ask in asks:

        if(float(ask[0]) < price and float(ask[2]) < 0):
            orders.append(ask)

    total_amount = round(sum(float(order[2]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Order Amount: {total_amount} at {price}")

    #append the total amount to the list
    if(currency == "USD"):
        bitfinex_usd.append(total_amount)
    elif(currency == "USDT"):
        bitfinex_usdt.append(total_amount)
    elif(currency == "EUR"):
        bitfinex_eur.append(total_amount)

    bids = data
    orders = []
    price = round(float(bids[0][0])*(1 - percentage/100))


    for bid in bids:

        if(float(bid[0]) > price and float(bid[2]) > 0):
            orders.append(bid)

    total_amount = round(sum(float(order[2]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Bid Amount: {total_amount} at {price}")

    #append the total amount to the list
    if(currency == "USD"):
        bitfinex_bids_usd.append(total_amount)
    elif(currency == "USDT"):
        bitfinex_bids_usdt.append(total_amount)
    elif(currency == "EUR"):
        bitfinex_bids_eur.append(total_amount)


def get_levels_bitflyer(data, percentage):
    asks = data["asks"]
    orders = []
    price = round(float(asks[0]["price"])*(1 + percentage/100))

    for ask in asks:
        if(float(ask["price"]) < price):
            orders.append(ask)

    total_amount = round(sum(float(order["size"]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Order Amount: {total_amount} at {price}")

    #append the total amount to the list
    bitflyer_jpy.append(total_amount)

    bids = data["bids"]
    orders = []
    price = round(float(bids[0]["price"])*(1 - percentage/100))

    for bid in bids:
        if(float(bid["price"]) > price):
            orders.append(bid)

    total_amount = round(sum(float(order["size"]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Bid Amount: {total_amount} at {price}")

    #append the total amount to the list
    bitflyer_bids_jpy.append(total_amount)

def get_levels_gemini(data, percentage):
    asks = data["asks"]
    orders = []
    price = round(float(asks[0]["price"])*(1 + percentage/100))

    for ask in asks:
        if(float(ask["price"]) < price):
            orders.append(ask)

    total_amount = round(sum(float(order["amount"]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Order Amount: {total_amount} at {price}")

    #append the total amount to the list
    gemini_usd.append(total_amount)

    bids = data["bids"]
    orders = []
    price = round(float(bids[0]["price"])*(1 - percentage/100))
    for bid in bids:
        if(float(bid["price"]) > price):
            orders.append(bid)

    total_amount = round(sum(float(order["amount"]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Bid Amount: {total_amount} at {price}")

    #append the total amount to the list
    gemini_bids_usd.append(total_amount)

# Read the Binance file and parse the bids
def parse_binance_file(file_path):
    bids = []
    asks = []
    with open(file_path, "r") as file:
        lines = file.readlines()
        is_bid_section = True
        for line in lines:
            if line.startswith("Asks:"):
                is_bid_section = False
                continue
            if line.startswith("Price:"):
                parts = line.split(", ")
                price = float(parts[0].split(": ")[1])
                quantity = float(parts[1].split(": ")[1])
                if is_bid_section:
                    bids.append([price, quantity])
                else:
                    asks.append([price, quantity])
    return {"bids": bids, "asks": asks}

# Update the file path


# Parse the Binance file
data_binance_usdt = parse_binance_file(api_file_binance_usdt)

# Filter and print bids greater than x% above the lowest ask
def get_levels_binance(data, percentage):
    asks = data["asks"]
    orders = []
    price = round(float(asks[0][0])*(1 + percentage/100))


    for ask in asks:
        if(float(ask[0]) < price):
            orders.append(ask)

    total_amount = round(sum(float(order[1]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Order Amount: {total_amount} at {price}")
    binance_usdt.append(total_amount)

    bids = data["bids"]
    orders = []
    price = round(float(asks[0][0])*(1 - percentage/100))
    for bid in bids:
        if(float(bid[0]) > price):
            orders.append(bid)

    total_amount = round(sum(float(order[1]) for order in orders))
    #print the total amount of orders and the price till the percentage in one line
    print(f"Total Bid Amount: {total_amount} at {price}")
    binance_bids_usdt.append(total_amount)


steps = 0.8







print("Coinbase USD")
#20 levels 5 steps
for i in range(30):
    get_levels_coinbase(data_coinbase_usd, steps*(i+1), "USD")

#usdt
print("Coinbase USDT")
#20    levels 5 steps
for i in range(30):
    get_levels_coinbase(data_coinbase_usdt, steps*(i+1), "USDT")

print("Coinbase EUR")
#20 levels 5 steps
for i in range(30):
    get_levels_coinbase(data_coinbase_eur, steps*(i+1), "EUR")




#bitfinex usd
print("Bitfinex USD")

for i in range(30):
    get_levels_bitfinex(data_bitfinex_usd, steps*(i+1), "USD")


#bitfinex usdt
print("Bitfinex USDT")
for i in range(30):
    get_levels_bitfinex(data_bitfinex_usdt, steps*(i+1), "USDT")
#bitfinex eur
print("Bitfinex EUR")
for i in range(30):
    get_levels_bitfinex(data_bitfinex_eur, steps*(i+1), "EUR")


#bitflyer
print("Bitflyer JPY")
for i in range(30):
    get_levels_bitflyer(data_bitflyer_jpy, steps*(i+1))

#gemini
print("Gemini USD")
for i in range(30):
    get_levels_gemini(data_gemini_usd, steps*(i+1))

#binance
print("Binance USDT")
for i in range(30):
    get_levels_binance(data_binance_usdt, steps*(i+1))




lowest_ask_coinbase_usd = float(data_coinbase_usd["asks"][0][0])
price_steps = [lowest_ask_coinbase_usd*(1 + steps/100*(i+1)) for i in range(30)]
price_steps_bids = [lowest_ask_coinbase_usd*(1 - steps/100*(i+1)) for i in range(30)]
#add up coinbase usd and coinbase eur

coinbase_total = [coinbase_usd[i] + coinbase_usdt[i] + coinbase_eur[i] for i in range(30)]
bitfinex_total = [-bitfinex_usd[i] + -bitfinex_usdt[i] + -bitfinex_eur[i] for i in range(30)]

coinbase_total_bids = [coinbase_bids_usd[i] + coinbase_bids_usdt[i] + coinbase_bids_eur[i] for i in range(30)]
bitfinex_total_bids = [bitfinex_bids_usd[i] + bitfinex_bids_usdt[i] + bitfinex_bids_eur[i] for i in range(30)]

#create a visualisation of the orderbook levels stack up total value added up for each percentag step
#should look symmetric like a exchange orderbook
import matplotlib.pyplot as plt


print(len(gemini_usd))
print(len(binance_usdt))

fig, ax = plt.subplots()

ax.plot(price_steps, coinbase_total, label='Coinbase Total', color='blue')
ax.plot(price_steps, bitfinex_total, label='Bitfinex Total', color="green")
ax.plot(price_steps, bitflyer_jpy, label='Bitflyer JPY', color="yellow")
ax.plot(price_steps, gemini_usd, label='Gemini USD', color="purple")
ax.plot(price_steps, binance_usdt, label='Binance USDT', color="orange")


#symmetric at the left side make price steps negative
ax.plot(price_steps_bids, coinbase_total_bids, label='Coinbase Total', color='blue')
ax.plot(price_steps_bids, bitfinex_total_bids, label='Bitfinex Total', color="green")
ax.plot(price_steps_bids, bitflyer_bids_jpy, label='Bitflyer JPY', color="yellow")
ax.plot(price_steps_bids, gemini_bids_usd, label='Gemini USD', color="purple")
ax.plot(price_steps_bids, binance_bids_usdt, label='Binance USDT', color="orange")




ax.set(xlabel='Percentage above lowest ask', ylabel='Total Order Amount',
       title='Orderbook Levels')
ax.grid()
#plt.legend()
fig.savefig("orderbook_levels.png")
#plt.show()






