예제 #1
0
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
예제 #2
0
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)
예제 #3
0
                           order_type='ioc')
    print(e.get_positions())


# 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')
예제 #4
0
start_pnl = e.get_pnl()
new_pnl = e.get_pnl()

timer = 0
#new_start_b = [average_b(20)]*10
#weighted_prices_b = new_start_b

while timer < 2000:
    stats_a = get_range_a(10000)
    stats_b = get_range_b(10000)

    max_range_a = stats_a[0] - stats_a[1]
    low_range_b = stats_b[1] - stats_b[2]

    book_a = e.get_last_price_book(philips_a)
    book_b = e.get_last_price_book(philips_b)

    if len(book_a.asks) != 0 and len(book_a.bids) != 0:
        current_ask_a = book_a.asks[0].price
        current_bid_a = book_a.bids[0].price
    if len(book_b.asks) != 0 and len(book_b.bids) != 0:
        current_ask_b = book_b.asks[0].price
        current_bid_b = book_b.bids[0].price
    #print(current_ask)

    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']
예제 #5
0
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)
예제 #6
0
# Returns all current positions
positions = e.get_positions()
for p in positions:
    print(p, positions[p])

# Returns all current positions with cash investedx
positions = e.get_positions_and_cash()
for p in positions:
    print(p, positions[p])

# Returns Current PnL based on last Traded Price
pnl = e.get_pnl()
print(pnl)

book_A = e.get_last_price_book("PHILIPS_A")
book_B = e.get_last_price_book("PHILIPS_B")
print('bids_PHILIPS_A:')
print("bid\tprice\task")
for i in reversed(book_A.asks):
    print('\t' + str(round(i.price, 1)) + '\t' + str(i.volume))
for i in book_A.bids:
    print(str(i.volume) + '\t' + str(round(i.price, 1)) + '\t')

# Returns all public tradeticks since the last time this function was called
tradeticks = e.poll_new_trade_ticks(instrument_id)
for t in tradeticks:
    print(
        f"[{t.instrument_id}] price({t.price}), volume({t.volume}), aggressor_side({t.aggressor_side}), buyer({t.buyer}), seller({t.seller})"
    )
예제 #7
0
#We track how our pnl changes
start_pnl = e.get_pnl()
new_pnl = e.get_pnl()
#Timer to report pnl changes every 10 'actions'
timer = 0
#new_start_b = [average_b(20)]*10
#weighted_prices_b = new_start_b

while timer<2000:
    stats_a = get_range_a(10000)
    stats_b = get_range_b(10000)
    
    max_range_a = stats_a[0]-stats_a[1] #We scale our purchase volume over the range we expect a typical fluctuation to occur
    low_range_b = stats_b[1]-stats_b[2]
    
    book_a = e.get_last_price_book(philips_a) #Obtain current books each round
    book_b = e.get_last_price_book(philips_b)
    
    if len(book_a.asks)!=0 and len(book_a.bids)!=0:
        current_ask_a = book_a.asks[0].price
        current_bid_a = book_a.bids[0].price
    if len(book_b.asks)!=0 and len(book_b.bids)!=0:
        current_ask_b = book_b.asks[0].price
        current_bid_b = book_b.bids[0].price
    #print(current_ask)
    
    average = average_b(2000)
    #print(average)
    positions = e.get_positions_and_cash()
    volume_left_a = positions[philips_a]['volume'] #Obtain Current Positions
    volume_left_b = positions[philips_b]['volume']
예제 #8
0
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}")
tradeticks = e.poll_new_trade_ticks(instrument_id)


def moving_avg(price_book):
    average = []
    t_end = time.time() + 10
    count = 0
    while time.time() < t_end:
        for i in price_book.bids:
            average.append(i.price)
예제 #9
0
INSTRUMENT = "PHILIPS_B"

e.poll_new_trades(INSTRUMENT)

diagonosticsOutput = ""

firstTrader = Trader(exchange=e,
                     instrument=INSTRUMENT,
                     instrumentB="PHILIPS_A",
                     orderVolume=ORDER_VOLUME,
                     weightingFactor=WEIGHTING_FACTOR,
                     volumeWeighting=VOLUME_WEIGHTING)
executing = True
count = 0
while executing:
    order_book = e.get_last_price_book(instrument_id="PHILIPS_A")
    # pnl.append(e.get_pnl)
    bidAskDict = firstTrader.trade()
    if count > TRADES:
        executing = False
    count += 1
    sleep(TIME_PERIOD)
    for t in (e.poll_new_trades("PHILIPS_B")):
        '''
        diagonosticsOutput += f"[TRADED {t.instrument_id}] price({t.price}), volume({t.volume}), side({t.side})\n"
        diagonosticsOutput += f"Asking in PHILIPS_B for {bidAskDict['ask']}, bidding in PHILIPS_B for {bidAskDict['bid']}\n"
        if order_book.asks and order_book.bids:
            diagonosticsOutput += f"Asking in PHILIPS_A for {order_book.asks[0].price}, bidding in PHILIPS_B for {order_book.bids[0].price}"
        '''
        Thread(target=firstTrader.hedge, args=(
            t,
예제 #10
0
import time
from optibook.synchronous_client import Exchange
from MainFunctions import getBestBid, getBestAsk
e = Exchange()
a = e.connect()

ABids = []
AAsks = []
BBids = []
BAsks = []

for i in range(300):
    ABook = e.get_last_price_book('PHILIPS_A')
    BBook = e.get_last_price_book('PHILIPS_B')

    ABids.append(getBestBid(ABook))
    AAsks.append(getBestAsk(ABook))
    BBids.append(getBestBid(BBook))
    BAsks.append(getBestAsk(BBook))
    time.sleep(1)

f = open("ABids.txt", "a")
for line in ABids:
    f.write(str(line) + "\n")
f.close()

f = open("BBids.txt", "a")
for line in BBids:
    f.write(str(line) + "\n")
f.close()
예제 #11
0
import logging
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")
import time
import pandas as pd
import os
import numpy as np

#CONNECT TO EXCHANGE
e = Exchange()
a = e.connect()
instrument_id = 'PHILIPS_A'
book = e.get_last_price_book('PHILIPS_A')
print(book.asks)
print(book.bids)

prices = dict()  # empty dict

print([price_vol.price for price_vol in book.asks])
print([price_vol.price for price_vol in book.bids])

instrument_id1 = 'PHILIPS_A'
instrument_id2 = 'PHILIPS_B'
books = e.get_last_price_book(instrument_id)


def print_table(books):
    print("bid | price | ask")
# Assume instrument A has higher liquidilty


# Work out the time lag between Philips A and Philips B
def get_lag():
    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
예제 #13
0
get_info()
# retreives the best bid/ask price from exchange. If the best bid price for B is greater than the best ask for A, sell to B and buy from A.

for i in range(0, 10000):

    positions = e.get_positions()
    #print("test")
    try:

        #print("B Bid : ", e.get_last_price_book('PHILIPS_B').bids[0].price)
        #print("A Ask : ", e.get_last_price_book('PHILIPS_A').asks[0].price)
        #print("B Ask : ", e.get_last_price_book('PHILIPS_B').asks[0].price)
        #print("A Bid : ", e.get_last_price_book('PHILIPS_A').bids[0].price)

        #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
        if ((e.get_last_price_book('PHILIPS_B').asks[0].price >
             e.get_last_price_book('PHILIPS_A').bids[0].price)
                and (e.get_last_price_book('PHILIPS_B').asks[0].price -
                     e.get_last_price_book('PHILIPS_A').bids[0].price) > .30):
            #if (e.get_last_price_book('PHILIPS_B').asks[0].price > e.get_last_price_book('PHILIPS_A').bids[0].price) :
            #print(f"First set of Conditions for Entry 1-2-3-4")
            volume = e.get_last_price_book('PHILIPS_B').bids[0].volume
            price_B = round(
                e.get_last_price_book('PHILIPS_B').asks[0].price, 3)
            price_A = round(
                e.get_last_price_book('PHILIPS_A').bids[0].price, 3)
            #print("Check Spread B-mid : ", price_B - (round((price_A + price_B) / 2 ,3)), " A-mid : ", (round((price_A + price_B) / 2 ,3))-price_A )
            mid_price = round((price_A + price_B) / 2, 3)
            diff = round(abs(price_A - mid_price), 3)
            if volume > 30:
                volume = 30
예제 #14
0
파일: main.py 프로젝트: veerte/arbitraggio
    # this function could also export statistics and data for further analysis if it were nexessary
            
last_trades_update = time.time()
last_position = (0, 0)
done = False
while not done:
    try:
        while not e.is_connected():
            print(timestamp() + 'disconnected, trying to reconnect...')
            time.sleep(1)
            e.connect()
            
        positions = e.get_positions()
        position = (positions.get(pha), positions.get(phb))
        
        if position != last_position:
            last_position = position
            trades = e.poll_new_trades(pha) + e.poll_new_trades(phb)
            if trades:
                summarize_trades(trades)
            print(timestamp() + f"==> POSITION: PHA: {position[0]}, PHB: {position[1]}")
        
        books = e.get_last_price_book(pha), e.get_last_price_book(phb)
        try_to_trade(0, books, position) # buy PHA, sell PHB
        try_to_trade(1, books, position) # buy PHB, sell PHA
        
    except KeyboardInterrupt:
        done = True
    except Exception as exc:
        print(timestamp() + "error: " + str(exc))
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('')
예제 #16
0
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")
#CONNECT TO EXCHANGE
e = Exchange()
a = e.connect()

# you can also define host/user/pass yourself
# when not defined, it is taken from ~/.optibook file if it exists
# if that file does not exists, an error is thrown

#e = Exchange(host='host-to-connect-to')
#a = e.connect(username='******', password='******')

trades = e.poll_new_trades(instrument_id)
for t in trades:
    print(
        f"[TRADED {t.instrument_id}] price({t.price}), volume({t.volume}), side({t.side})"
    )

positions = e.get_positions()
for p in positions:
    print(p, positions[p])
print("\n")

book = e.get_last_price_book('PHILIPS_A')
book_b = e.get_last_price_book("PHILIPS_B")

books = (book, book_b)

# print(book.asks)
# print(book.bids)
예제 #18
0
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
        if ((e.get_last_price_book('PHILIPS_B').asks[0].price >
             e.get_last_price_book('PHILIPS_A').bids[0].price)
                and (e.get_last_price_book('PHILIPS_B').asks[0].price -
                     e.get_last_price_book('PHILIPS_A').bids[0].price) > .30):
            #if (e.get_last_price_book('PHILIPS_B').asks[0].price > e.get_last_price_book('PHILIPS_A').bids[0].price) :
예제 #19
0
e = Exchange()
a = e.connect()

# Returns all current positions
# positions = e.get_positions()
# for p in positions:
#     print(p, positions[p])
#     print("-----------------------------")
#     # print(e.get_outstanding_orders(p))
#     # print("-----------------------------")
#     print(e.get_last_price_book(p).asks)
#     print(e.get_last_price_book(p).bids)

while True:
    if  len(e.get_last_price_book(instrument_id1).bids)  == 0 or \
        len(e.get_last_price_book(instrument_id1).asks)  == 0 or \
        len(e.get_last_price_book(instrument_id2).bids)  == 0 or \
        len(e.get_last_price_book(instrument_id2).asks)  == 0:
            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