# DO NOT COPY: TOP SECRET
from math import ceil
from random import uniform
from secret_trading_tools import tradables_except_kollar, flip_a_coin, cheapest_buy_order, best_sell_order, \
    place_order, some_orders_on, buy, sell, old_order_is_expired, delete_order_on, \
    transactions_size_since_last_order_on, order_on


def create_order_on(tradable):
    """
    This function places a new order on the given tradable
    """
    limit = uniform(cheapest_buy_order, best_sell_order)

    duration = 43200

    some_orders = some_orders_on(tradable)  # returns us roughly math.log2(x) orders where x is the total # of orders
    some_amounts = [order.amount for order in some_orders]
    amount = ceil(sum(some_amounts) / len(some_amounts))

    stop_loss = False

    if flip_a_coin() == 'heads':
        buy(tradable, amount, limit, stop_loss, duration)
    else:
        sell(tradable, amount, limit, stop_loss, duration)


for tradable in tradables_except_kollar:
    create_order_on(tradable)

while True:
    for tradable in tradables_except_kollar:
        if old_order_is_expired(tradable):
            delete_order_on(tradable)
            create_order_on(tradable)

        if transactions_size_since_last_order_on(tradable) > 2 * order_on(tradable).amount:
            delete_order_on(tradable)
            create_order_on(tradable)