def test_instrument(self): E1 = ExchangeType("E1") E2 = ExchangeType("E2") E3 = ExchangeType("E3") i1 = Instrument( "TestInst", exchange=E1, broker_id="1", ) i2 = Instrument( "TestInst", exchange=E2, broker_id="2", broker_exchange="test", ) i3 = Instrument( "TestInst", exchange=E3, broker_id="3", ) assert i1.tradingLines() == [i1, i2, i3] assert i2.tradingLines() == [i1, i2, i3] assert i3.tradingLines() == [i1, i2, i3]
def __init__(self, trading_type, verbose, account='', delayed=True, **kwargs): self._trading_type = trading_type self._verbose = verbose if self._trading_type == TradingType.LIVE: super().__init__(ExchangeType('interactivebrokers')) else: super().__init__(ExchangeType('interactivebrokerspaper')) # map order.id to order self._orders = {} # IB TWS gateway self._order_event_queue = Queue() self._market_data_queue = Queue() self._contract_lookup_queue = Queue() self._account_position_queue = Queue() self._api = _API(account, self.exchange(), delayed, self._order_event_queue, self._market_data_queue, self._contract_lookup_queue, self._account_position_queue)
def __init__(self, trading_type, verbose, api_key="", api_secret="", api_passphrase="", **kwargs): self._trading_type = trading_type self._verbose = verbose # coinbase keys self._api_key = api_key or os.environ.get("API_KEY", "") self._api_secret = api_secret or os.environ.get("API_SECRET", "") self._api_passphrase = api_passphrase or os.environ.get( "API_PASSPHRASE", "") # enforce authentication, otherwise we don't get enough # data to be interesting if not (self._api_key and self._api_secret and self._api_passphrase): raise Exception("No coinbase auth!") # don't implement backtest for now if trading_type == TradingType.BACKTEST: raise NotImplementedError() if self._trading_type == TradingType.SANDBOX: # Coinbase sandbox super().__init__(ExchangeType("coinbaseprosandbox")) else: # Coinbase Live trading print("*" * 100) print("*" * 100) print("WARNING: LIVE TRADING") print("*" * 100) print("*" * 100) super().__init__(ExchangeType("coinbasepro")) # Create an exchange client based on the coinbase docs # Note: cbpro doesnt seem to work as well as I remember, # and ccxt has moved to a "freemium" model where coinbase # pro now costs money for full access, so here i will just # implement the api myself. self._client = CoinbaseExchangeClient( self._trading_type, self.exchange(), self._api_key, self._api_secret, self._api_passphrase, ) # list of market data subscriptions self._subscriptions: List[Instrument] = []
def __init__(self, trading_type, verbose, api_key, is_sandbox, timeframe='1y', start_date=None, end_date=None): super().__init__(ExchangeType('iex')) self._trading_type = trading_type self._verbose = verbose self._api_key = api_key self._is_sandbox = is_sandbox if trading_type == TradingType.LIVE: assert not is_sandbox self._timeframe = timeframe if timeframe == 'live': assert trading_type != TradingType.BACKTEST if timeframe == '1d': # intraday testing # TODO if today is weekend/holiday, pick last day with data self._start_date = datetime.strptime(start_date, '%Y%m%d') if start_date else datetime.today() self._end_date = datetime.strptime(end_date, '%Y%m%d') if end_date else datetime.today() self._subscriptions = [] # "Order" management self._queued_orders = deque() self._order_id = 1
def __init__(self, trading_type=None, verbose=False, **kwargs): self._trading_type = trading_type self._verbose = verbose if self._trading_type == TradingType.LIVE: super().__init__(ExchangeType('interactivebrokers')) else: super().__init__(ExchangeType('interactivebrokerspaper')) # map order.id to order self._orders = {} # IB TWS gateway self._order_event_queue = Queue() self._market_data_queue = Queue() self._api = _API(self._order_event_queue, self._market_data_queue)
def __init__(self, trading_type, verbose, filename: str, value_field=''): super().__init__(ExchangeType('csv-{}'.format(filename))) self._trading_type = trading_type self._verbose = verbose self._filename = filename self._data: List[Trade] = [] self._value_field = value_field
def _make_cpp_order( volume, price, side, instrument, exchange=ExchangeType(""), notional=0.0, order_type=OrderType.MARKET, flag=OrderFlag.NONE, stop_target=None, id=None, timestamp=None, ): """helper method to ensure all arguments are setup""" return OrderCpp( id or "0", timestamp or datetime.now(), volume, price, side, instrument, exchange, notional, order_type, flag, stop_target, )
def __init__(self, trading_type, verbose, filename: str): super().__init__(ExchangeType('csv-{}'.format(filename))) self._trading_type = trading_type self._verbose = verbose self._filename = filename self._data: List[Trade] = [] self._queued_orders = deque() # type: ignore self._order_id = 1
def __init__(self, trading_type, verbose): super().__init__(ExchangeType('testharness')) self._trading_type = trading_type self._verbose = verbose self._instrument = Instrument('Test.inst', InstrumentType.EQUITY) self._id = 0 self._start = datetime.now() - timedelta(days=30) self._client_order = None
def __init__(self, trading_type: TradingType, verbose: bool) -> None: super().__init__(ExchangeType("testharness")) self._trading_type = trading_type self._verbose = verbose self._instrument = Instrument("Test.inst", InstrumentType.EQUITY) self._id = 0 self._start = datetime.now() - timedelta(days=30) self._client_order: Optional[Order] = None
def __init__(self, trading_type: TradingType, verbose: bool, account: str = "", delayed: bool = True, **kwargs: dict) -> None: self._trading_type = trading_type self._verbose = verbose if self._trading_type == TradingType.LIVE: super().__init__(ExchangeType("interactivebrokers")) else: super().__init__(ExchangeType("interactivebrokerspaper")) # map order.id to order self._orders: Dict[str, Order] = {} # map order id to received event self._order_received_map: Dict[str, asyncio.Event] = {} self._order_received_res: Dict[str, bool] = {} # map order id to cancelled event self._order_cancelled_map: Dict[str, asyncio.Event] = {} self._order_cancelled_res: Dict[str, bool] = {} # track "finished" orders so we can ignore them self._finished_orders: Set[str] = set() # IB TWS gateway self._order_event_queue: Queue[Dict[str, Union[str, int, float]]] = Queue() self._market_data_queue: Queue[Dict[str, Union[str, int, float, Instrument]]] = Queue() self._contract_lookup_queue: Queue[Contract] = Queue() self._account_position_queue: Queue[Position] = Queue() self._api = _API( account, self.exchange(), delayed, self._order_event_queue, self._market_data_queue, self._contract_lookup_queue, self._account_position_queue, )
def __init__(self, trading_type, verbose, filename: str): super().__init__(ExchangeType("csv-{}".format(filename))) self._trading_type = trading_type self._verbose = verbose self._filename = filename self._data: List[Trade] = [] # "Order" management self._queued_orders: Deque[Order] = deque() self._order_id = 1
def test_stop_order_validation(self): if _in_cpp(): return with pytest.raises(AssertionError): Order(volume=0.0, price=5.0, side=Order.Sides.SELL, exchange=ExchangeType(''), order_type=Order.Types.STOP, stop_target=Order( volume=0.5, price=5.0, side=Order.Sides.SELL, exchange=ExchangeType(''), order_type=Order.Types.STOP, instrument=_INSTRUMENT, ), instrument=_INSTRUMENT)
def test_maker_orders_validation(self): if not os.environ.get('AAT_USE_CPP'): with pytest.raises(Exception): o = Order(volume=0.0, price=5.0, side=Order.Sides.SELL, order_type=Order.Types.LIMIT, exchange=ExchangeType(''), instrument=_INSTRUMENT) Trade(maker_orders=deque(), taker_order=o)
def test_maker_orders_validation(self): if not os.environ.get('AAT_USE_CPP'): with pytest.raises(pydantic.ValidationError): o = Order(id=1, timestamp=datetime.now(), volume=0.0, price=5.0, side=Order.Sides.SELL, order_type=Order.Types.LIMIT, exchange=ExchangeType(''), instrument=_INSTRUMENT) Trade(id=1, timestamp=datetime.now(), volume=0.0, price=0.0, side=Order.Sides.SELL, exchange=ExchangeType(''), instrument=_INSTRUMENT, maker_orders=deque(), taker_order=o)
def __init__(self, trading_type, verbose, api_key, is_sandbox): super().__init__(ExchangeType('iex')) self._trading_type = trading_type self._verbose = verbose self._api_key = api_key self._is_sandbox = is_sandbox self._subscriptions = [] # "Order" management self._queued_orders = deque() self._order_id = 1
def test_instrument_calendar_getter(self): t = TradingDay() e = ExchangeType("test-exchange") i = Instrument( "TestTradingDayInst", exchange=e, trading_day=t, ) assert i.tradingDay == t
def test_price_level_iter(self): pl = _PriceLevel(5, _Collector()) orders = [ Order(10 + i, 5, Side.BUY, Instrument('TEST'), ExchangeType(""), 0.0, OrderType.LIMIT, OrderFlag.NONE, None) for i in range(2) ] for o in orders: # This causes a segfault pl.add(o) for o, op in zip(orders, pl): assert o == op
def __init__(self, trading_type, verbose, account="", delayed=True, **kwargs): self._trading_type = trading_type self._verbose = verbose if self._trading_type == TradingType.LIVE: super().__init__(ExchangeType("interactivebrokers")) else: super().__init__(ExchangeType("interactivebrokerspaper")) # map order.id to order self._orders = {} # map order id to received event self._order_received_map: Dict[str, asyncio.Event] = {} self._order_received_res: Dict[str, bool] = {} # map order id to cancelled event self._order_cancelled_map: Dict[str, asyncio.Event] = {} self._order_cancelled_res: Dict[str, bool] = {} # IB TWS gateway self._order_event_queue = Queue() self._market_data_queue = Queue() self._contract_lookup_queue = Queue() self._account_position_queue = Queue() self._api = _API( account, self.exchange(), delayed, self._order_event_queue, self._market_data_queue, self._contract_lookup_queue, self._account_position_queue, )
def test_stop_order_validation(self): if _in_cpp(): return with pytest.raises(pydantic.ValidationError): Order(id=1, timestamp=datetime.now(), volume=0.0, price=5.0, side=Order.Sides.SELL, exchange=ExchangeType(''), order_type=Order.Types.STOP, stop_target=Order( id=1, timestamp=datetime.now(), volume=0.5, price=5.0, side=Order.Sides.SELL, exchange=ExchangeType(''), order_type=Order.Types.STOP, instrument=_INSTRUMENT, ), instrument=_INSTRUMENT)
def _seed(ob, instrument, flag=OrderFlag.NONE): x = .5 while x < 10.0: side = Side.BUY if x <= 5 else Side.SELL order = Order(volume=1.0, price=x, side=side, instrument=instrument, exchange=ExchangeType(""), order_type=OrderType.LIMIT, flag=flag) order.id = "1" ob.add(order) x += .5
def _seed(ob, instrument, flag=OrderFlag.NONE): x = .5 while x < 10.0: side = Side.BUY if x <= 5 else Side.SELL ob.add(Order(id=1, timestamp=datetime.now(), volume=1.0, price=x, side=side, instrument=instrument, exchange=ExchangeType(""), filled=0.0, order_type=OrderType.LIMIT, flag=flag)) x += .5
def __init__(self, trading_type, verbose, api_key='', api_secret='', api_passphrase='', **kwargs): self._trading_type = trading_type self._verbose = verbose if trading_type == TradingType.BACKTEST: raise NotImplementedError() if self._trading_type == TradingType.SANDBOX: super().__init__(ExchangeType('coinbaseprosandbox')) else: super().__init__(ExchangeType('coinbasepro')) auth = api_key and api_secret and api_passphrase self._public_client = PublicClient() if trading_type == TradingType.SANDBOX: self._auth_client = AuthenticatedClient( api_key, api_secret, api_passphrase, api_url="https://api-public.sandbox.pro.coinbase.com" ) if auth else None else: self._auth_client = AuthenticatedClient( api_key, api_secret, api_passphrase) if auth else None # TODO self._subscriptions = [] self._ws_client = WebsocketClient(url="wss://ws-feed.pro.coinbase.com", products="BTC-USD")
def __init__( self, instrument: Instrument, exchange_name: Union[ExchangeType, str] = "", callback: Optional[Callable] = None, ) -> None: self._instrument = instrument self._exchange_name: ExchangeType = (exchange_name if isinstance( exchange_name, ExchangeType) else ExchangeType(exchange_name or "")) self._callback = callback or self._push # reset levels and collector self.reset() # default callback is to enqueue self._queue: "Queue[Event]" = Queue()
def __init__( self, trading_type: TradingType, verbose: bool, api_key: str, is_sandbox: bool, timeframe: str = "1y", start_date: str = "", end_date: str = "", cache_data: bool = True, ) -> None: super().__init__(ExchangeType("iex")) self._trading_type = trading_type self._verbose = verbose self._api_key = api_key self._is_sandbox = is_sandbox self._cache_data = cache_data if trading_type == TradingType.LIVE: assert not is_sandbox self._timeframe = timeframe if timeframe == "live": assert trading_type != TradingType.BACKTEST if timeframe == "1d": # intraday testing # TODO if today is weekend/holiday, pick last day with data self._start_date = (datetime.strptime(start_date, "%Y%m%d") if start_date else datetime.today()) self._end_date = (datetime.strptime(end_date, "%Y%m%d") if end_date else datetime.today()) self._subscriptions: List[Instrument] = [] # "Order" management self._queued_orders: Deque[Order] = deque() self._order_id = 1
def __init__(self, trading_type: TradingType, verbose: bool, api_key: str = "", api_secret: str = "", api_passphrase: str = "", order_book_level: str = "trades", satoshis: bool = False, **kwargs: dict) -> None: self._trading_type = trading_type self._verbose = verbose # coinbase keys self._api_key = api_key or os.environ.get("API_KEY", "") self._api_secret = api_secret or os.environ.get("API_SECRET", "") self._api_passphrase = api_passphrase or os.environ.get( "API_PASSPHRASE", "") # order book level to track if order_book_level not in ("l3", "l2", "trades"): raise NotImplementedError( "`order_book_level` must be in (l3, l2, trades)") self._order_book_level = order_book_level # enforce authentication, otherwise we don't get enough # data to be interesting if not (self._api_key and self._api_secret and self._api_passphrase): raise Exception("No coinbase auth!") # don't implement backtest for now if trading_type == TradingType.BACKTEST: raise NotImplementedError() # don't implement simulation for now if trading_type == TradingType.BACKTEST: raise NotImplementedError() if self._trading_type == TradingType.SANDBOX: # Coinbase sandbox super().__init__(ExchangeType("coinbaseprosandbox")) else: # Coinbase Live trading print("*" * 100) print("*" * 100) print("WARNING: LIVE TRADING") print("*" * 100) print("*" * 100) super().__init__(ExchangeType("coinbasepro")) # multiply by 100,000,000 and do everything in integer volumes self._satoshis = satoshis # Create an exchange client based on the coinbase docs # Note: cbpro doesnt seem to work as well as I remember, # and ccxt has moved to a "freemium" model where coinbase # pro now costs money for full access, so here i will just # implement the api myself. self._client = CoinbaseExchangeClient( self._trading_type, self.exchange(), self._api_key, self._api_secret, self._api_passphrase, self._satoshis, ) # list of market data subscriptions self._subscriptions: List[Instrument] = []
def __init__(self, trading_type: TradingType, verbose: bool) -> None: super().__init__(ExchangeType("kafka")) self._trading_type = trading_type self._verbose = verbose
async def onPeriodic(self) -> None: o = Order(1, 1, Side.BUY, self.instruments()[0], ExchangeType("testharness")) _ = await self.newOrder(o) self._orders.append(o)
def __init__(self, trading_type, verbose): super().__init__(ExchangeType('kafka')) self._trading_type = trading_type self._verbose = verbose
async def onPeriodic(self): o = await self.newOrder( Order(1, 1, Side.BUY, self.instruments()[0], ExchangeType('testharness'))) self._orders.append(o)