import random from datetime import timedelta, datetime from math import log2, ceil import model order_expiry = 43200 def place_order(ownable_id): cheapest_buy_order, best_sell_order = model.abs_spread(ownable_id) if cheapest_buy_order is None or best_sell_order is None: return investors_id = model.bank_id() orders = model.get_ownable_orders(investors_id, ownable_id) orders = [random.choice(orders) for _ in range(int(ceil(log2(len(orders)))))] amounts = [order[3] for order in orders] amount = sum(amounts) / len(amounts) expiry = datetime.strptime(model.current_db_time(), '%Y-%m-%d %H:%M:%S') + timedelta(minutes=order_expiry) model.place_order(buy=bool(random.getrandbits(1)), ownership_id=model.get_ownership_id(ownable_id, investors_id), limit=random.uniform(cheapest_buy_order, best_sell_order), stop_loss=False, amount=amount, expiry=expiry) def main(): # TODO testen """the initial part of the trading bot algorithm""" if model.get_user_orders(model.bank_id()): raise AssertionError('The trading bot already has some orders.') if input('Are you sure you want to set the trading bots initial orders? (type in "yes" or something else):') == 'yes': for ownable_id in model.ownable_ids(): if ownable_id != model.currency_id(): place_order(ownable_id) else: print('Not placing orders.') model.cleanup() if __name__ == '__main__': main() def notify_expired_orders(orders): for order in orders: # order_id = order[0] ownership_id = order[1] # check if that was one of the bots orders bank_ownership_id = model.get_ownership_id(ownership_id, model.bank_id()) if ownership_id != bank_ownership_id: continue # create a new order ownable_id = model.ownable_id_by_ownership_id(ownership_id) place_order(ownable_id) def notify_order_traded(ownable_id): """ Called after a trade has been done and now the auctions are finished. :param ownable_id: the ownable that was traded :return: True iff a new order was placed """ model.connect() if ownable_id == model.currency_id(): return False ownership_id = model.get_ownership_id(ownable_id, model.bank_id()) model.cursor.execute(''' SELECT rowid, amount, expiry FROM orders WHERE ownership_id = ? -- no need for ORDER since the bot should have only one order -- ORDER BY rowid DESC -- equivalent to ordering by time created LIMIT 1 ''', (ownership_id,)) my_last_order = model.cursor.fechtone() last_order_id = my_last_order[0] last_amount = my_last_order[1] expiry = my_last_order[2] dt_order_placed = datetime.strptime(expiry, '%Y-%m-%d %H:%M:%S') - timedelta(minutes=order_expiry) model.cursor.execute(''' SELECT 2 * SUM(amount) >= ? FROM transactions WHERE ownable_id = ? AND dt >= ? ''', (last_amount, ownable_id, dt_order_placed)) if model.cursor.fechtone()[0]: model.delete_order(last_order_id) place_order(ownable_id) return True return False