# DO NOT COPY: TOP SECRET
# Illegal publishing will be charged with up to ₭500
from math import ceil
from random import uniform

from secret_trading_tools import tradables_except_kollar, best_buy_order, cheapest_sell_order, \
    some_orders_on, buy, sell, old_order_is_just_expired, delete_order_on, \
    transactions_size_since_last_order_on, order_on, own_money, owned_amount, some_order_has_just_been_executed


def follower():
    """
    The main algorithm
    """
    for tradable in tradables_except_kollar:
        create_order_on(tradable)

    while True:
        for tradable in tradables_except_kollar:
            if old_order_is_just_expired(tradable):
                create_order_on(tradable)

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


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

    duration = 43200

    some_orders = some_orders_on(tradable)  # returns us roughly 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 limit - best_buy_order < cheapest_sell_order - limit:
        if limit * amount < own_money:
            buy(tradable, amount, limit, stop_loss, duration)
    else:
        if amount < owned_amount(tradable):
            sell(tradable, amount, limit, stop_loss, duration)


if __name__ == '__main__':
    follower()