def make_orders(exchange: Exchange, orders: List[Order]): # Orders in form of [Order] order_results = list( map( lambda order: exchange.insert_order(order.instrument_id, price=order.price, volume=order.volume, side=order.side, order_type=order.order_type), orders)) for (order, order_id) in zip(orders, order_results): trade_history = exchange.get_trade_history(order.instrument_id) if len(trade_history) > 0 and trade_history[-1].order_id == order_id: success_msg = "SUCCESS " elif order.order_type == "ioc": success_msg = "FAILED " else: success_msg = "OUTSTANDING" order_log = f"Order: {order_id} {success_msg} | Instrument: {order.instrument_id} | Price: {order.price:.1f} | Volume: {order.volume} | Side: {order.side} | Order Type: {order.order_type}" g_recent_orders.pop(0) g_recent_orders.append(order_log) print(order_log)
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')
if volume > 3: volume = 3 #if volume > 10: if ((price_A - mid_price) / 2 > (mid_price - price_B)): if ((positions['PHILIPS_B'] > -instrument_limit1 or positions['PHILIPS_A'] < instrument_limit1) and abs(positions['PHILIPS_B']) + abs(positions['PHILIPS_A']) < 400): print("sell B at:", price_B, " and buy A:", price_A, " for", volume, " lots") result = e.insert_order('PHILIPS_B', price=price_B, volume=volume, side='ask', order_type='ioc') print(f"Order Id: {result} 1 B-ask") #if result != None: #result = e.insert_order('PHILIPS_A', price=price_A, volume=volume, side='bid', order_type='ioc') print(f"Order Id: {result} 2 A-bid") # clearing of positions using limit order from weighted mid price mid_price = round((price_A + price_B) / 2, 3) diff = round(abs(price_A - mid_price), 3) print(mid_price) print(mid_price + .10)
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') #print(f"Order Id: {result}")
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)
# bid, volume p, price 1 - 'I want to buy p units at price 1' # ask, volume p, price 1 - 'I want to sell p units at price 1' # print(e.get_trade_history(instrument_id)) #book = e.get_last_price_book(instrument_id) #print(book.bids) #print(book.asks) # current positions print(e.get_positions_and_cash()) processed_order_book = e.get_last_price_book(instrument_id) print("bid | price | ask") for level in processed_order_book: print(f"{level.bid_volume}|{level.price_level}|{level.ask_volume}") # e.insert_order(instrument_id, price=71.70, volume=1, side='bid', order_type='limit') """ # buy something e.insert_order(instrument_id, price=70, volume=1, side='bid', order_type='limit') print(e.get_positions_and_cash()) time.sleep(1) # sell something e.insert_order(instrument_id, price=71, volume=1, side='ask', order_type='limit') print(e.get_positions_and_cash()) """
average = average_b(2000) #print(average) positions = e.get_positions_and_cash() volume_left_a = positions[philips_a]['volume'] volume_left_b = positions[philips_b]['volume'] # if current_bid_a-np.mean(weighted_prices_a)>1.5: # SELLING A WHEN HIGH if current_bid_a > np.mean(weighted_prices_a) and volume_left_a > -200: price = current_bid_a volume = max(int(10 * (current_bid_a - stats_a[1]) / max_range_a), 1) buying_order = e.insert_order(philips_a, price=current_bid_a, volume=float(volume), side='ask', order_type='limit') print('Selling %s A at price %s ****** Expect to buy at %s' % (volume, current_bid_a, np.mean(weighted_prices_a))) bought_prices.append(price) updated_weights = [price] * volume weighted_prices_a = updated_weights + weighted_prices_a time.sleep(1) timer += 1 # BUYING A WHEN LOW if current_ask_a < np.mean(weighted_prices_a) and volume_left_a < 200: sell_volume = min( int(10 * (np.mean(weighted_prices_a) - current_ask_a) * max_range_a), np.abs(volume_left_a))
instrument=INSTRUMENT, instrumentB="PHILIPS_A", orderVolume=ORDER_VOLUME, weightingFactor=WEIGHTING_FACTOR, volumeWeighting=VOLUME_WEIGHTING) executing = True count = 0 while executing: firstTrader.trade() firstTrader.hedge() # This is a last-minute strategy to take advantage of other people's inefficient algorithms # We set up very favourable orders in an attempt to catch those without appropriate checks on their order volume and price e.insert_order("PHILIPS_B", price=20.1, volume=300, side="bid", order_type="limit") e.insert_order("PHILIPS_B", price=139.9, volume=300, side="ask", order_type="limit") if count > TRADES: executing = False count += 1 sleep(TIME_PERIOD) print(diagonosticsOutput) firstTrader.close()
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)
time.sleep(TIME_DELAY) data, prev_data = get_data(e, prev_data) moving_sum.append((data[0][2] + data[1][2])/2) if len(moving_sum) > MAX_HISTORY: moving_sum.pop(0) momentum = sum(moving_sum[-MOMENTUM_HISTORY:])/MOMENTUM_HISTORY moving_ave = sum(moving_sum)/len(moving_sum) moving_ave = (momentum + moving_ave) / 2 print(moving_ave) positions = e.get_positions() if data[0][0] > moving_ave + THRESHOLD and positions["PHILIPS_A"] > -MAX_POSITION: #PHILIPS_A is buying at above moving_ave + THRESHOLD #time to sell result = e.insert_order("PHILIPS_A", price=data[0][0], volume=VOLUME, side='ask', order_type='ioc') print("created order to sell PHILIPS_A") elif data[0][1] < moving_ave - THRESHOLD and positions["PHILIPS_A"] < MAX_POSITION: #PHILIPS_A is selling at below moving_ave - THRESHOLD #time to buy result = e.insert_order("PHILIPS_A", price=data[0][1], volume=VOLUME, side='bid', order_type='ioc') print("created order to buy PHILIPS_A") elif data[1][0] > moving_ave + THRESHOLD and positions["PHILIPS_B"] > -MAX_POSITION: #PHILIPS_B is buying at above moving_ave + THRESHOLD #time to sell result = e.insert_order("PHILIPS_B", price=data[1][0], volume=VOLUME, side='ask', order_type='ioc') print("created order to sell PHILIPS_B") elif data[1][1] < moving_ave - THRESHOLD and positions["PHILIPS_B"] < MAX_POSITION: #PHILIPS_B is selling at below moving_ave - THRESHOLD #time to buy result = e.insert_order("PHILIPS_B", price=data[1][1], volume=VOLUME, side='bid', order_type='ioc')
return 5 #execute lowLiq = "PHILIPS_B" highLiq = "PHILIPS_A" count_trades = 0 while (count_trades < 10): hLBook = e.get_last_price_book(highLiq) bestAsk = getBestAsk(hLBook) if (bestAsk is not None): e.insert_order(highLiq, price=bestAsk + 0.1, volume=5, side='ask', order_type='limit') time.sleep(get_lag() - 2) currentTradeId = e.insert_order(lowLiq, price=bestAsk, volume=5, side='bid', order_type='limit') print("Sell to A") count_trades = count_trades + 1 #trades = e.poll_new_trades("PHILIPS_B") time.sleep(3) if (e.get_outstanding_orders("PHILIPS_B").values()): # While there are still outstanding orders e.insert_order(highLiq,
from optibook.synchronous_client import Exchange from MainFunctions import getBestBid 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.bids[0].volume >= abs(totalPosition)): print("Estimated cash by end") cash = e.get_cash() bestBid = getBestBid(book) gain = bestBid * abs(totalPosition) print(cash + gain) print("Proceed?") if (input() == "y"): e.insert_order(instr, price=bestBid, volume=abs(totalPosition), side='ask', order_type='ioc') time.sleep(5)
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')
time.sleep(0.25) else: A_best_bid = e.get_last_price_book(instrument_id1).bids[0].price A_best_ask = e.get_last_price_book(instrument_id1).asks[0].price B_best_bid = e.get_last_price_book(instrument_id2).bids[0].price B_best_ask = e.get_last_price_book(instrument_id2).asks[0].price # print(A_best_bid, A_best_ask, B_best_bid, B_best_ask) if A_best_bid > B_best_ask: A_best_bid_vol = e.get_last_price_book(instrument_id1).bids[0].volume B_best_ask_vol = e.get_last_price_book(instrument_id2).asks[0].volume volume = min(A_best_bid_vol, B_best_ask_vol) result = e.insert_order(instrument_id1, price = A_best_bid, volume=volume, side='bid', order_type='limit') result = e.insert_order(instrument_id2, price = B_best_ask, volume=volume, side='ask', order_type='limit') print(f"Order Id: {result}") if B_best_bid > A_best_ask: A_best_ask_vol = e.get_last_price_book(instrument_id1).asks[0].volume B_best_bid_vol = e.get_last_price_book(instrument_id2).bids[0].volume volume = min(A_best_ask_vol, B_best_bid_vol) result = e.insert_order(instrument_id2, price = B_best_bid, volume=volume, side='bid', order_type='limit') result = e.insert_order(instrument_id1, price = A_best_ask, volume=volume, side='ask', order_type='limit') print(f"Order Id: {result}") time.sleep(0.25)