Exemplo n.º 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
Exemplo n.º 2
0
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 connect():
    logger = logging.getLogger('client')
    logger.setLevel('ERROR')

    print("Setup was successful.")

    e = Exchange()
    if not e.is_connected():
        e.connect()
        print('connected')
    else:
        print('already connected')

    return e
Exemplo n.º 4
0
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')
Exemplo n.º 5
0
from optibook.synchronous_client import Exchange
import time
import matplotlib.pyplot as plt
import numpy as np
import logging

logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

e = Exchange()
a = e.connect()

philips_a = 'PHILIPS_A'
philips_b = 'PHILIPS_B'

### Generally Creating Useful Functions for The Future ###


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


my_position()


# Delete all outstanding orders
Exemplo n.º 6
0
#IMPORT EXCHANGE
from optibook.synchronous_client import Exchange
import time

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)
Exemplo n.º 7
0
from optibook.synchronous_client import Exchange
from trader3 import Trader
from time import sleep
from threading import Thread

# Use README for more detail on strategy and functions

e = Exchange()
a = e.connect()

TIME_PERIOD = 0.13
TIME_RUNNING = 1200
TRADES = TIME_RUNNING / TIME_PERIOD
ORDER_VOLUME = 24
WEIGHTING_FACTOR = 0.1 / ORDER_VOLUME
VOLUME_WEIGHTING = 1 / 2
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:
Exemplo n.º 8
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")
Exemplo n.º 9
0
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')
Exemplo n.º 10
0
from optibook.synchronous_client import Exchange
from utils import get_data, check_arbitrage, withdraw_orders, check_our_position, adjust_ask_price, adjust_bid_price, position_overload

import logging
import time
import random
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

instrument_id1 = 'PHILIPS_A'
instrument_id2 = 'PHILIPS_B'

e = Exchange()
a = e.connect()

# get_data

TIME_DELAY = 0.25

position_state = 0
prev_data = None
# for i in range(10):
while True:
    e_instance = e
    data, prev_data = get_data(e_instance, prev_data)
    if data is None:
        print("no market data exists")
        time.sleep(TIME_DELAY)
        continue
Exemplo n.º 11
0
from optibook.synchronous_client import Exchange
from utils import *

import logging
import time
import random
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")


e = Exchange()
a = e.connect()

prev_data = None
moving_ave = 0
moving_sum = []

MAX_HISTORY = 20 #number of historical prices referenced for moving_ave
MOMENTUM_HISTORY = 5 
THRESHOLD = 0.1 #deviation from moving_ave threshold before entering the market
TIME_DELAY = 0.25 #frequency of cycle
VOLUME = 3 #volume per trade
MAX_POSITION = 20 #max absolute position allowed on either instrument

while True:
    time.sleep(TIME_DELAY)
    
    data, prev_data = get_data(e, prev_data)
    moving_sum.append((data[0][2] + data[1][2])/2)
Exemplo n.º 12
0
from optibook.synchronous_client import Exchange
import logging
import time
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

instrument_id = 'PHILIPS_A'

e = Exchange()
a = e.connect()


def get_out_of_positions():
    # 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(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())


# bid, volume p, price 1 - 'I want to buy p units at price 1'
Exemplo n.º 13
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)
Exemplo n.º 14
0
from optibook.synchronous_client import Exchange

import logging
import time
# from utils import check_our_position, get_data
e = Exchange()
a = e.connect()
# for i in range(100):
pb1 = e.get_last_price_book("PHILIPS_A")
pb2 = e.get_last_price_book("PHILIPS_B")

print(pb1.bids, pb1.asks, pb2.bids, pb2.asks)
# time.sleep(0.1)
Exemplo n.º 15
0
#IMPORT EXCHANGE
from optibook.synchronous_client import Exchange

import logging
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

#INSTRUMENT
instrument_id = 'PHILIPS_A'

#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:
Exemplo n.º 16
0
from optibook.synchronous_client import Exchange
from trader2 import Trader
from time import sleep
from threading import Thread
# import matplotlib as plt

e = Exchange()
a = e.connect()

# pnl = []

TIME_PERIOD = 0.2
TIME_RUNNING = 300
TRADES = TIME_RUNNING / TIME_PERIOD
ORDER_VOLUME = 5
WEIGHTING_FACTOR = 0.1 / ORDER_VOLUME  #0.001
VOLUME_WEIGHTING = 1 / 2
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
Exemplo n.º 17
0
import time
from optibook.synchronous_client import Exchange
e = Exchange()
a = e.connect()
instrument_id = 'PHILIPS_A'
# Returns all current positions
positions = e.get_positions()
for p in positions:
    print(p, positions[p])

book = e.get_last_price_book(instrument_id)
print(book.bids[0].price)
print(book.asks)

#problem 1


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

#Problem 6
print("bid | price | ask")
for i in book.asks:
    print(" | "+str(i.price)+" | "+str(i.volume))
    
for i in book.bids:
    print(str(i.volume)+" | "+str(i.price)+" | ")


def whether_to_trade():
Exemplo n.º 18
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()
Exemplo n.º 19
0
import time
import logging

from optibook.synchronous_client import Exchange

from strategy import should_kill_attempt, arbitrage, stoikov_mm
from utils import balance_positions
from moving_average import MovingAverage

logging.getLogger('client').setLevel('ERROR')

exchange = Exchange()
exchange.connect()

START_PNL = exchange.get_pnl()

ma_A = MovingAverage(exchange, "PHILIPS_A")

tick = 1

while not should_kill_attempt(exchange, START_PNL):
    time.sleep(0.11)

    print(f"tick {tick}")
    tick += 1

    ma_A.update()

    # Don't want to balance our trades from our MM positions
    exchange.delete_orders("PHILIPS_A")
from optibook.synchronous_client import Exchange

import logging
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")
e = Exchange()
a = e.connect()

last_bid_price = 0
last_ask_price = 0
instrument_id = "PHILIPS_A"
# GOAL - return the best bid and best ask price, or create one
while True:
    order_book = e.get_last_price_book(instrument_id=instrument_id)
    """
    #print(order_book.timestamp)
    #print(order_book.instrument_id)
    print(order_book.bids)
    print(order_book.asks)
    
    """
    if not order_book.bids:
        best_bid = last_bid_price
    if not order_book.asks:
        best_ask = last_ask_price
        # INDEPDENT
    if order_book.bids and order_book.asks:
        best_bid = order_book.bids[0].price
        best_ask = order_book.asks[0].price
Exemplo n.º 21
0
 def __init__(self):
     self.e = Exchange()
     logging.info(self.e.connect())
     logging.info("Setup was successful.")
Exemplo n.º 22
0
import dual_market_strat
import safe_dual_strat
import difference_strat
import extremes_strat
import dual_paper_strat
import dual_hedge_strat
import mimic_strat
import sys

logger = logging.getLogger('client')
logger.setLevel('INFO')


# Main loop: run a number of different strategies
if __name__ == '__main__':
    exchange = Exchange()
    logging.info(exchange.connect())
    logging.info("Setup was successful.")
    try:
        # we can run multiple strategies at once, but really having separate bots to do this would be simpler
        # since currently we can't ignore our own orders in aggregate data such as the pricebook
        # strats = [dual_market_strat.DualMarketStrat(exchange, ["PHILIPS_A", "PHILIPS_B"])]
        # strats = [safe_dual_strat.SafeDualStrat(exchange, ["PHILIPS_A", "PHILIPS_B"])]
        # strats = [difference_strat.DifferenceStrat(exchange, ["PHILIPS_A", "PHILIPS_B"])]
        #strats = [dual_paper_strat.DualPaperStrat(exchange, ["PHILIPS_A", "PHILIPS_B"])]
        strats = [dual_hedge_strat.DualHedgeStrat(exchange, "PHILIPS_A", "PHILIPS_B")]
        while True:
            time.sleep(0.2)
            for s in strats:
                try:
                    s.update();
Exemplo n.º 23
0
from optibook.synchronous_client import Exchange

import logging
logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

instrument_id = 'PHILIPS_A'

e = Exchange()
a = e.connect()

print("Exchange connected")

#print(e.is_connected())
#result = e.insert_order(instrument_id, price=1., volume=1, side='bid', order_type='limit')
#print(f"Order Id: {result}")
#print(e.is_connected())

orders = e.get_outstanding_orders(instrument_id)
for o in orders.values():
    print(o)
print(orders)

print("Orders checked")
Exemplo n.º 24
0
def connect():
    global exchange
    exchange = Exchange()
    return exchange.connect()
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('')
Exemplo n.º 26
0
from optibook.synchronous_client import Exchange

import logging

logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

instrument_id = 'PHILIPS_A'

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='******')

# Returns all currently outstanding orders
orders = e.get_outstanding_orders(instrument_id)
for o in orders.values():
    print('outstanding orders: ' + o)

# Returns all trades you have done since the last time this function was called
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})"
Exemplo n.º 27
0
 def __init__(self):
     self.exchange_client = Exchange()
Exemplo n.º 28
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)
Exemplo n.º 29
0
import time

from optibook.synchronous_client import Exchange

import logging

logger = logging.getLogger('client')
logger.setLevel('ERROR')

print("Setup was successful.")

# compare the bid and ask prices of the two instruments

e = Exchange()
a = e.connect()

instrument_limit = 190
instrument_limit1 = 100
orderBatch = 0


def get_info():
    #print("in get_info")
    print(e.get_positions())
    positions = e.get_positions()
    for p in positions:
        print(p, positions[p])

    pnl = e.get_pnl()
    print("current pnl is", pnl)
import time
from optibook.synchronous_client import Exchange
from MainFunctions import getBestAsk, printTrades, printOutstanding

e = Exchange()
a = e.connect()

# 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)