def balance_positions(exchange: Exchange, total_threshold: int = 100, individual_threshold: int = 350): positions = exchange.get_positions() pos_a, pos_b = positions["PHILIPS_A"], positions["PHILIPS_B"] total_position = pos_a + pos_b if balance_individual(exchange, positions, "PHILIPS_A", 200, individual_threshold) or \ balance_individual(exchange, positions, "PHILIPS_B", 200, individual_threshold): return True if total_position > total_threshold: sell_all_positions( exchange, positions, max_a=get_best_price(exchange.get_last_price_book("PHILIPS_A"), "sell"), max_b=get_best_price(exchange.get_last_price_book("PHILIPS_B"), "sell"), target=total_threshold / 4) elif total_position < -total_threshold: buy_all_positions( exchange, positions, min_a=get_best_price(exchange.get_last_price_book("PHILIPS_A"), "buy"), min_b=get_best_price(exchange.get_last_price_book("PHILIPS_B"), "buy"), target=total_threshold / 4) return False
def clear_all_positions(exchange: Exchange) -> None: """ Clear all positions without regard to loss """ for s, p in exchange.get_positions().items(): if p > 0: exchange.insert_order(s, price=1, volume=p, side='ask', order_type='ioc') elif p < 0: exchange.insert_order(s, price=100000, volume=-p, side='bid', order_type='ioc')
# retreives the best bid/ask price from exchange. If the best bid price for B is greater than the best ask for A, Buy from A and Sell to B # Identify which Exchange to buy and sell at : Philips A more liquid & Philips B less liquid - So check for arbitrage & high Vols # Idea is to buy off from exchange with greater Bid and sell to the other exchange # else stick to buying from more illiquid exchange and sell to less liquid exchange def whicheXchange(): if PA_BID != PB_BID && VA_BID < VB_BID : TradedBib = VA_BID TradedVol = VA_BID else TradedBib = VA_BID TradedVol = VA_BID """ for i in range(0, 10000): positions = e.get_positions() #print("test") try: PA_BID = round(e.get_last_price_book('PHILIPS_B').bids[0].price, 3) PA_ASK = round(e.get_last_price_book('PHILIPS_A').asks[0].price, 3) PB_BID = round(e.get_last_price_book('PHILIPS_A').bids[0].price, 3) PB_ASK = round(e.get_last_price_book('PHILIPS_B').asks[0].price, 3) VA_BID = e.get_last_price_book('PHILIPS_A').bids[0].volume VB_BID = e.get_last_price_book('PHILIPS_B').bids[0].volume VA_ASK = e.get_last_price_book('PHILIPS_A').asks[0].volume VA_ASK = e.get_last_price_book('PHILIPS_B').asks[0].volume whicheXchange() #if (e.get_last_price_book('PHILIPS_B').asks[0].price > e.get_last_price_book('PHILIPS_A').asks[0].price and e.get_last_price_book('PHILIPS_B').bids[0].price < e.get_last_price_book('PHILIPS_A').bids[0].price and
from optibook.synchronous_client import Exchange import time import logging from statistics import mean import random logger = logging.getLogger('client') logger.setLevel('ERROR') print("Setup was successful.") e = Exchange() a = e.connect() print(e.get_positions()) for s, p in e.get_positions().items(): if p > 0: e.insert_order(s, price=1, volume=p, side='ask', order_type='ioc') elif p < 0: e.insert_order(s, price=100000, volume=-p, side='bid', order_type='ioc') print(e.get_positions()) instrument_id = 'PHILIPS_A' book = e.get_last_price_book(instrument_id) print(book.bids) instrument_id = 'PHILIPS_A' #result = e.insert_order(instrument_id, price=98, volume=40, side='bid', order_type='limit')
class AutoTrader: """ This is the "main" class which houses our algorithm. You will see there are a few helper functions already here, as well as a main "trade" function which runs the algorithm. We've done some work for you already there, but you will need to write the bulk of the strategy yourself. """ def __init__(self): self.exchange_client = Exchange() def connect(self): """ Connect to the optibook exchange """ self.exchange_client.connect() def get_order_book_for_instrument(self, instrument): return self.exchange_client.get_last_price_book(instrument) def get_position_for_instrument(self, instrument): positions = self.exchange_client.get_positions() return positions[instrument] def get_top_of_book(self, order_book): """ Get the best bid and best ask of the order book you pass in as a parameter. """ best_bid_price = None best_bid_volume = None if len(order_book.bids) > 0: best_bid_price = round(order_book.bids[0].price, 2) best_bid_volume = round(order_book.bids[0].volume, 2) best_ask_price = None best_ask_volume = None if len(order_book.asks) > 0: best_ask_price = round(order_book.asks[0].price, 2) best_ask_volume = round(order_book.asks[0].volume, 2) return TopOfBook(best_bid_price, best_bid_volume, best_ask_price, best_ask_volume) def print_top_of_book(self, instrument, top_of_book): print( f'[{instrument}] bid({top_of_book.best_bid_volume}@{top_of_book.best_bid_price})-ask({top_of_book.best_ask_volume}@{top_of_book.best_ask_price})' ) def insert_buy_order(self, instrument, price, volume, order_type): """ Insert an order to buy. Note that volume must be positive. Also note that you have no guarantee that your order turns into a trade. instrument: str The name of the instrument to buy. price: float The price level at which to insert the order into the order book on the bid side. volume: int The volume to buy. order_type: int You can set this to 'limit' or 'ioc'. 'limit' orders stay in the book while any remaining volume of an 'ioc' that is not immediately matched is cancelled. return: an InsertOrderReply containing a request_id as well as an order_id, the order_id can be used to e.g. delete or amend the limit order later. """ return self.exchange_client.insert_order(instrument, price=price, volume=volume, side='bid', order_type=order_type) def insert_sell_order(self, instrument, price, volume, order_type): """ Insert an order to sell. Note that volume must be positive. Also note that you have no guarantee that your order turns into a trade. instrument: str The name of the instrument to sell. price: float The price level at which to insert the order into the order book on the ask side. volume: int The volume to sell. order_type: int You can set this to 'limit' or 'ioc'. 'limit' orders stay in the book while any remaining volume of an 'ioc' that is not immediately matched is cancelled. return: an InsertOrderReply containing a request_id as well as an order_id, the order_id can be used to e.g. delete or amend the limit order later. """ return self.exchange_client.insert_order(instrument, price=price, volume=volume, side='ask', order_type=order_type) def increase(self, array): last = array[0] for element in array: if (element < last): return False last = element return True def decrease(self, array): last = array[0] for element in array: if (element > last): return False last = element return True def trade(self): """ This function is the main trading algorithm. It is called in a loop, and in every iteration of the loop we do the exact same thing. We start by getting the order books, formatting them a little bit and then you will have to make a trading decision based on the prices in the order books. """ # First we get the current order books of both instruments full_book_liquid = self.get_order_book_for_instrument( LIQUID_INSTRUMENT) full_book_illiquid = self.get_order_book_for_instrument( ILLIQUID_INSTRUMENT) # Then we extract the best bid and best ask from those order books top_book_liquid = self.get_top_of_book(full_book_liquid) top_book_illiquid = self.get_top_of_book(full_book_illiquid) # If either the bid side or ask side is missing, in the order books, then we stop right here and wait for the # next cycle, in the hopes that then the order books will have both the bid and ask sides present if not top_book_liquid.has_bid_and_ask( ) or not top_book_illiquid.has_bid_and_ask(): print( 'There are either no bids or no asks, skipping this trade cycle.' ) return # Print the top of each book, this will be very helpful to you when you want to understand what your # algorithm is doing. Feel free to add more logging as you see fit. self.print_top_of_book(LIQUID_INSTRUMENT, top_book_liquid) self.print_top_of_book(ILLIQUID_INSTRUMENT, top_book_illiquid) print('') # Trade! # Take if from here, and implement your actual strategy with the help of the pre-processing we have done for you # above. Note that this is very rudimentary, and there are things we have left out (e.g. position management is # missing, hedging is missing, and how much credit you ask for is also missing). # # Maybe a first step is to run this code as is, and see what it prints out to get some inspiration if you are # stuck. Otherwise, come to us, we are always happy to help. Check the client documentation for all the # functions that are at your disposal. # # ----------------------------------------- # TODO: Implement trade logic here ''' instruments = ['PHILIPS_A', 'PHILIPS_B'] SIZE = 5 for index, instrument in enumerate(instruments): asks[index].append(self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_ask_price) if len(asks[index]) > SIZE: asks[index].pop(0) bids[index].append(self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_bid_price) if len(bids[index]) > SIZE: bids[index].pop(0) print(asks) print(bids) positions = self.exchange_client.get_positions() stocks = positions[instrument] if (len(bids[index]) == SIZE and self.increase(bids[index])): print("stocks"+str(stocks)) doTrade = self.insert_sell_order(instrument, self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_bid_price, max(1, int(stocks * 1/5)), 'ioc') # come back and change volume print("sell") elif len(asks[index]) == SIZE and self.decrease(asks[index]) and (positions[instruments[1]] + positions[instruments[0]]) <200: print("positions: " + str(positions[instrument])) doTrade = self.insert_buy_order(instrument, self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_ask_price, 1, 'ioc') #change volvume print("buy") ''' ''' instruments = ['PHILIPS_A', 'PHILIPS_B'] SIZE = 100 for index, instrument in enumerate(instruments): aux = self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_ask_price if aux: asks[index].append(aux) if len(asks[index]) > SIZE: asks[index].pop(0) aux = self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_bid_price bids[index].append(aux) if len(bids[index]) > SIZE: bids[index].pop(0) if SIZE == len(asks[index]): averageAsk = sum(asks[index]) / len(asks) averageBid = sum(bids[index]) / len(bids) positions = self.exchange_client.get_positions() stocks = positions[instrument] if averageBid > self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_bid_price and abs(stocks) < 100: print(abs(stocks)) doTrade = self.insert_buy_order(instrument, self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_bid_price - 0.5, , 'ioc') print("buy") if averageAsk < self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_ask_price : doTrade = self.insert_sell_order(instrument, self.get_top_of_book(self.get_order_book_for_instrument(instrument)).best_ask_price + 0.5, max(1, int(stocks * 1/2)), 'ioc') # come back and change volume print("sell") ''' bidA = None askB = None instruments = ['PHILIPS_A', 'PHILIPS_B'] SIZE = 1 while (not askB) or (not bidA): bidA = self.get_top_of_book( self.get_order_book_for_instrument( instruments[0])).best_bid_price askB = self.get_top_of_book( self.get_order_book_for_instrument( instruments[1])).best_ask_price if bidA - askB > 0 and askB < 1000: doTrade = self.insert_sell_order(instruments[0], bidA, SIZE, 'ioc') doTrade = self.insert_buy_order(instruments[1], askB, SIZE, 'ioc') print("bidA and askB") bidB = None askA = None while (not askA) or (not bidB): bidB = self.get_top_of_book( self.get_order_book_for_instrument( instruments[1])).best_bid_price askA = self.get_top_of_book( self.get_order_book_for_instrument( instruments[0])).best_ask_price if bidB - askA > 0 and askA < 1000: doTrade = self.insert_sell_order(instruments[1], bidB, SIZE, 'ioc') doTrade = self.insert_buy_order(instruments[0], askA, SIZE, 'ioc') print("bidB and askA")
class AutoTrader: """ This is the "main" class which houses our algorithm. You will see there are a few helper functions already here, as well as a main "trade" function which runs the algorithm. We've done some work for you already there, but you will need to write the bulk of the strategy yourself. """ def __init__(self): self.exchange_client = Exchange() def connect(self): """ Connect to the optibook exchange """ self.exchange_client.connect() def get_order_book_for_instrument(self, instrument): return self.exchange_client.get_last_price_book(instrument) def get_position_for_instrument(self, instrument): positions = self.exchange_client.get_positions() return positions[instrument] def get_top_of_book(self, order_book): """ Get the best bid and best ask of the order book you pass in as a parameter. """ best_bid_price = None best_bid_volume = None if len(order_book.bids) > 0: best_bid_price = round(order_book.bids[0].price, 2) best_bid_volume = round(order_book.bids[0].volume, 2) best_ask_price = None best_ask_volume = None if len(order_book.asks) > 0: best_ask_price = round(order_book.asks[0].price, 2) best_ask_volume = round(order_book.asks[0].volume, 2) return TopOfBook(best_bid_price, best_bid_volume, best_ask_price, best_ask_volume) def print_top_of_book(self, instrument, top_of_book): print( f'[{instrument}] bid({top_of_book.best_bid_volume}@{top_of_book.best_bid_price})-ask({top_of_book.best_ask_volume}@{top_of_book.best_ask_price})' ) def insert_buy_order(self, instrument, price, volume, order_type): """ Insert an order to buy. Note that volume must be positive. Also note that you have no guarantee that your order turns into a trade. instrument: str The name of the instrument to buy. price: float The price level at which to insert the order into the order book on the bid side. volume: int The volume to buy. order_type: int You can set this to 'limit' or 'ioc'. 'limit' orders stay in the book while any remaining volume of an 'ioc' that is not immediately matched is cancelled. return: an InsertOrderReply containing a request_id as well as an order_id, the order_id can be used to e.g. delete or amend the limit order later. """ return self.exchange_client.insert_order(instrument, price=price, volume=volume, side='bid', order_type=order_type) def insert_sell_order(self, instrument, price, volume, order_type): """ Insert an order to sell. Note that volume must be positive. Also note that you have no guarantee that your order turns into a trade. instrument: str The name of the instrument to sell. price: float The price level at which to insert the order into the order book on the ask side. volume: int The volume to sell. order_type: int You can set this to 'limit' or 'ioc'. 'limit' orders stay in the book while any remaining volume of an 'ioc' that is not immediately matched is cancelled. return: an InsertOrderReply containing a request_id as well as an order_id, the order_id can be used to e.g. delete or amend the limit order later. """ return self.exchange_client.insert_order(instrument, price=price, volume=volume, side='ask', order_type=order_type) def trade(self): """ This function is the main trading algorithm. It is called in a loop, and in every iteration of the loop we do the exact same thing. We start by getting the order books, formatting them a little bit and then you will have to make a trading decision based on the prices in the order books. """ # First we get the current order books of both instruments full_book_liquid = self.get_order_book_for_instrument( LIQUID_INSTRUMENT) full_book_illiquid = self.get_order_book_for_instrument( ILLIQUID_INSTRUMENT) # Then we extract the best bid and best ask from those order books top_book_liquid = self.get_top_of_book(full_book_liquid) top_book_illiquid = self.get_top_of_book(full_book_illiquid) # If either the bid side or ask side is missing, in the order books, then we stop right here and wait for the # next cycle, in the hopes that then the order books will have both the bid and ask sides present if not top_book_liquid.has_bid_and_ask( ) or not top_book_illiquid.has_bid_and_ask(): print( 'There are either no bids or no asks, skipping this trade cycle.' ) return # Print the top of each book, this will be very helpful to you when you want to understand what your # algorithm is doing. Feel free to add more logging as you see fit. self.print_top_of_book(LIQUID_INSTRUMENT, top_book_liquid) self.print_top_of_book(ILLIQUID_INSTRUMENT, top_book_illiquid) print('')
class Bot: instruments = ["PHILIPS_A", "PHILIPS_B"] def __init__(self): self.e = Exchange() logging.info(self.e.connect()) logging.info("Setup was successful.") def get_out_of_positions(self): # Get out of all positions you are currently holding, regardless of the loss involved. That means selling whatever # you are long, and buying-back whatever you are short. Be sure you know what you are doing when you use this logic. print(self.e.get_positions()) for s, p in self.e.get_positions().items(): if p > 0: self.e.insert_order(s, price=1, volume=p, side='ask', order_type='ioc') elif p < 0: self.e.insert_order(s, price=100000, volume=-p, side='bid', order_type='ioc') print(self.e.get_positions()) # Logging functions def log_new_trade_ticks(self): logger.info("Polling new trade ticks") for i in self.instruments: tradeticks = self.e.poll_new_trade_ticks(i) for t in tradeticks: logger.info( f"[{t.instrument_id}] price({t.price}), volume({t.volume}), aggressor_side({t.aggressor_side}), buyer({t.buyer}), seller({t.seller})" ) def log_positions_cash(self): logger.info(self.e.get_positions_and_cash()) def log_all_outstanding_orders(self): for i in self.instruments: logger.info(self.e.get_outstanding_orders(i)) def wait_until_orders_complete(self): orders_outstanding = True while orders_outstanding: orders_outstanding = False for i in self.instruments: if len(self.e.get_outstanding_orders(i)) > 0: orders_outstanding = True self.log_all_outstanding_orders() #time.sleep(0.1) def mainloop(self): while True: # check for trade differences # m1 ask < m2 bid #logger.info("Checking for discrepancies:") books = [self.e.get_last_price_book(x) for x in self.instruments] for m1, m2 in [(0, 1), (1, 0)]: m1_id = self.instruments[m1] m2_id = self.instruments[m2] try: m1_ask = books[m1].asks[0] m2_bid = books[m2].bids[0] if m1_ask.price < m2_bid.price: logger.info( f"Can profit: buy {m1_id} at {m1_ask} and sell {m2_id} at {m2_bid}" ) self.e.insert_order(m1_id, price=m1_ask.price, volume=1, side='bid', order_type='limit') self.e.insert_order(m2_id, price=m2_bid.price, volume=1, side='ask', order_type='limit') self.log_all_outstanding_orders() self.wait_until_orders_complete() self.log_positions_cash() except Exception as e: print(logger.error(e)) continue time.sleep(1.0 / 25)
from optibook.synchronous_client import Exchange from MainFunctions import getBestAsk import time e = Exchange() a = e.connect() instr_ids = ['PHILIPS_A', 'PHILIPS_B'] index = int(input()) # 0 or 1 instr = instr_ids[index] book = e.get_last_price_book(instr) positions = e.get_positions().values() totalPosition = sum(positions) if (book.asks[0].volume >= abs(totalPosition)): print("Estimated cash by end") cash = e.get_cash() bestAsk = getBestAsk(book) loss = bestAsk * abs(totalPosition) print(cash - loss) print("Proceed?") if (input() == "y"): e.insert_order(instr, price=bestAsk, volume=abs(totalPosition), side='bid', order_type='ioc') time.sleep(5)
""" if ((abs(positions1['PHILIPS_B']) + abs(positions1['PHILIPS_A'])) > 100 or abs(positions1['PHILIPS_B']) > instrument_limit or abs(positions1['PHILIPS_A']) > instrument_limit): #time.sleep(1) print(e.get_positions()) for s, p in e.get_positions().items(): if p > 0: e.insert_order(s, price=1, volume=round(p/4,0), side='ask', order_type='ioc') elif p < 0: e.insert_order(s, price=100000, volume=-round(p/4,0), side='bid', order_type='ioc') print(e.get_positions()) """ print("POS : ", e.get_positions()) positions1 = e.get_positions() if ((abs(positions1['PHILIPS_B']) + abs(positions1['PHILIPS_A'])) > 250 or abs(positions1['PHILIPS_B']) > instrument_limit or abs(positions1['PHILIPS_A']) > instrument_limit): time.sleep(1) print(e.get_positions()) for s, p in e.get_positions().items(): if p > 0: e.insert_order(s, price=1, volume=round(p / 4, 0), side='ask',
from optibook.synchronous_client import Exchange e = Exchange() a = e.connect() # Simple algorithm to clear all current positions so that it is easier to test hedging algorithms for s, p in e.get_positions().items(): if p > 0: e.insert_order(s, price=1, volume=p, side='ask', order_type='ioc') elif p < 0: e.insert_order(s, price=100000, volume=-p, side='bid', order_type='ioc')
for t in trades: print( f"[TRADED {t.instrument_id}] price({t.price}), volume({t.volume}), side({t.side})" ) printOutstanding() i = 0 outstanding = e.get_outstanding_orders("PHILIPS_A") for o in outstanding.values(): print( f"Outstanding order: order_id({o.order_id}), instrument_id({o.instrument_id}), price({o.price}), volume({o.volume}), side({o.side})" ) outstanding = e.get_outstanding_orders("PHILIPS_B") for o in outstanding.values(): print( f"Outstanding order: order_id({o.order_id}), instrument_id({o.instrument_id}), price({o.price}), volume({o.volume}), side({o.side})" ) trades = e.get_trade_history('PHILIPS_A') for t in trades: print( f"[TRADED {t.instrument_id}] price({t.price}), volume({t.volume}), side({t.side})" ) trades = e.get_trade_history('PHILIPS_B') for t in trades: print( f"[TRADED {t.instrument_id}] price({t.price}), volume({t.volume}), side({t.side})" ) print(e.get_positions())