def read_orderbook_from_file(filename):
    bids = {}
    asks = {}
    with open(filename, 'r') as file:
        current_section = None
        for line in file:
            line = line.strip()
            if line == "Bids:":
                current_section = "bids"
            elif line == "Asks:":
                current_section = "asks"
            elif line:
                price, quantity = line.split(", ")
                price = float(price.split(": ")[1])
                quantity = float(quantity.split(": ")[1])
                if current_section == "bids":
                    bids[price] = quantity
                elif current_section == "asks":
                    asks[price] = quantity
    return bids, asks


def print_bids_asks_within_5_percent(bids_data, asks_data):
    highest_bid_price = max(bids_data.keys())
    threshold = 0.05 * highest_bid_price
    total_bids_within_threshold = sum(
        quantity for price, quantity in bids_data.items() if price >= highest_bid_price - threshold)
    total_asks_within_threshold = sum(
        quantity for price, quantity in asks_data.items() if price <= highest_bid_price + threshold)

    print("Total Bids within 5% of Highest Bid:", total_bids_within_threshold)
    print("Total Asks within 5% of Highest Bid:", total_asks_within_threshold)


# Read data from orderbook.txt
orderbook_filename = "orderbook.txt"
bids_data, asks_data = read_orderbook_from_file(orderbook_filename)

# Calculate total bids and asks
total_bids = sum(bids_data.values())
total_asks = sum(asks_data.values())

print("Total Bids:", total_bids)
print("Total Asks:", total_asks)

print_bids_asks_within_5_percent(bids_data, asks_data)
