Example #1
0
    def sample_time_series(self):
        ds = ModelFactory.build_time_series(series_id="HSI.BAR.86400",
                                            desc="HSI",
                                            keys=["high", "low", "close"],
                                            inputs='HSI.BAR.1',
                                            input_keys=['close', 'open'],
                                            default_output_key="close",
                                            missing_value_replace=0)
        ModelFactory.add_time_series_item(ds,
                                          timestamp=0,
                                          data={
                                              "high": 350.00,
                                              "low": 200.45,
                                              "close": 250.1
                                          })
        ModelFactory.add_time_series_item(ds,
                                          timestamp=1,
                                          data={
                                              "high": 1350.00,
                                              "low": 1200.45,
                                              "close": 1250.1
                                          })

        return ds
 def get_series(self,
                key,
                create_if_missing=True,
                cls=DataSeries,
                desc=None,
                missing_value=np.nan):
     if type(key) == str:
         if key not in self.__series_dict:
             self.__series_dict[key] = cls(
                 time_series=ModelFactory.build_time_series(
                     series_id=key,
                     series_cls=get_full_cls_name(cls),
                     desc=desc,
                     missing_value_replace=missing_value))
         return self.__series_dict[key]
     raise AssertionError()
Example #3
0
 def sample_order_replace_request(self):
     req = ModelFactory.build_order_replace_request(0,
                                                    "BuyLowSellHigh",
                                                    "1",
                                                    "2",
                                                    type=Limit,
                                                    qty=4954.1,
                                                    limit_price=123.2,
                                                    stop_price=123.2,
                                                    tif=DAY,
                                                    oca_tag="23",
                                                    params={
                                                        "testparam1": "1",
                                                        "testparam2": "2"
                                                    })
     return req
Example #4
0
    def __init__(self, time_series: TimeSeries = None, series_id: str = None):

        self.data_list = []
        self.time_list = []
        self.data_time_dict = {}
        self.last_item = None
        self.subject = Subject()
        self.time_series = time_series if time_series else ModelFactory.build_time_series(
            series_id=series_id)
        self.name = self.time_series.series_id

        if hasattr(time_series, 'items') and time_series.items:
            for item in time_series.items:
                self.add(timestamp=item.timestamp,
                         data=dict(item.data),
                         init=True)
Example #5
0
    def sample_execution_report(self):
        event = ModelFactory.build_execution_report(
            1,
            "IB",
            "event_123",
            broker_ord_id="broker_1234",
            cl_id="BuyLowSellHigh",
            cl_ord_id="clOrdId_1",
            inst_id="HSI@SEHK",
            last_qty=100.1,
            last_price=21.1,
            commission=0.8,
            filled_qty=1231.0,
            avg_price=123.1,
            status=New)

        return event
Example #6
0
    def sample_bar(self):
        bar = ModelFactory.build_bar("HSI@SEHK",
                                     Bar.Time,
                                     86400,
                                     provider_id='IB',
                                     timestamp=12312,
                                     utc_time=12312,
                                     begin_time=12300,
                                     open=123,
                                     high=300,
                                     low=30,
                                     close=156,
                                     vol=500,
                                     adj_close=324,
                                     open_interest=123)

        return bar
Example #7
0
    def __send_exec_report(self, new_ord_req, last_price, last_qty, ord_status):
        commission = self.commission.calc(new_ord_req, last_price, last_qty)
        ord_id = self.clordid_ordid_map[new_ord_req.cl_id][new_ord_req.cl_ord_id]
        exec_report = ModelFactory.build_execution_report(
            timestamp=self.clock.now(),
            broker_id=Broker.Simulator,
            broker_event_id=self.next_event_id(),
            broker_ord_id=ord_id,
            cl_id=new_ord_req.cl_id,
            cl_ord_id=new_ord_req.cl_ord_id,
            inst_id=new_ord_req.inst_id,
            last_qty=last_qty,
            last_price=last_price,
            status=ord_status,
            commission=commission)

        self.exec_handler.on_exec_report(exec_report)
Example #8
0
def build_subscription_requests(feed_id, instruments, subscription_types, from_date=None, to_date=None):
    reqs = []
    for instrument in instruments:
        for subscription_type in subscription_types:
            attrs = subscription_type.split(".")
            md_type = get_subscription_type(attrs[0])
            md_provider_id = attrs[1]
            bar_type = get_bar_type(attrs[2]) if md_type == MarketDataSubscriptionRequest.Bar else None
            bar_size = get_bar_size(attrs[3]) if md_type == MarketDataSubscriptionRequest.Bar else None

            reqs.append(ModelFactory.build_market_data_subscription_request(type=md_type,
                                                                            inst_id=instrument.inst_id,
                                                                            feed_id=feed_id,
                                                                            md_provider_id=md_provider_id,
                                                                            bar_type=bar_type,
                                                                            bar_size=bar_size,
                                                                            from_date=from_date,
                                                                            to_date=to_date))
    return reqs
Example #9
0
 def sample_new_order_request(self):
     req = ModelFactory.build_new_order_request(0,
                                                "BuyLowSellHigh",
                                                "1",
                                                portf_id="TestPortf",
                                                broker_id="Simulator",
                                                inst_id="HSI@SEHK",
                                                action=Buy,
                                                type=Limit,
                                                qty=4954.1,
                                                limit_price=123.2,
                                                stop_price=123.2,
                                                tif=DAY,
                                                oca_tag="23",
                                                params={
                                                    "testparam1": "1",
                                                    "testparam2": "2"
                                                })
     return req
Example #10
0
class PlotTest(TestCase):
    values = [44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42,
              45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00]

    factory = ModelFactory()

    def __create_plot(self):
        series = DataSeries(time_series=TimeSeries())
        t = 20170101
        for idx, value in enumerate(self.values):
            ts = datestr_to_unixtimemillis(t)
            series.add(timestamp=ts, data={"value": value})
            t = t + 1
        values = series.get_series(["value"])
        plot = TimeSeriesPlot(values)

        return plot

    def test_plot(self):
        plot = self.__create_plot()
        self.assertIsNotNone(plot)
Example #11
0
def load_inst_from_row(data_store, row):
    alt_symbols = {}
    if 'alt_symbols' in row and row['alt_symbols']:
        for item in row['alt_symbols'].split(";"):
            kv = item.split("=")
            alt_symbols[kv[0]] = kv[1]
    inst = ModelFactory.build_instrument(symbol=row['symbol'],
                                         type=row['type'],
                                         primary_exch_id=row['exch_id'],
                                         ccy_id=row['ccy_id'],
                                         name=row['name'],
                                         sector=row['sector'],
                                         industry=row['industry'],
                                         margin=row['margin'],
                                         alt_symbols=alt_symbols,
                                         underlying_ids=row['und_inst_id'],
                                         option_type=row['put_call'],
                                         strike=row['strike'],
                                         exp_date=row['expiry_date'],
                                         multiplier=row['factor'])
    data_store.save_instrument(inst)
Example #12
0
    def __init__(self,
                 time_series=None,
                 inputs=None,
                 input_keys=None,
                 desc=None,
                 keys: List[str] = None,
                 default_output_key: str = 'value',
                 **kwargs):
        if not time_series:
            series_id = build_series_id(self.__class__.__name__, inputs,
                                        input_keys, **kwargs)
            time_series = ModelFactory.build_time_series(
                series_id=series_id,
                series_cls=get_full_cls_name(self),
                desc=desc,
                inputs=inputs,
                input_keys=input_keys,
                keys=keys,
                default_output_key=default_output_key,
                **kwargs)

        super(Indicator, self).__init__(time_series=time_series)
        self.calculate = True
        self.__raw_inputs = self._convert_raw_input(inputs=inputs)
 def add(self, timestamp, value):
     self.append_row(timestamp, value)
     self.subject.on_next(
         ModelFactory.build_time_series_update_event(source=self.series_id, timestamp=timestamp,
                                                     data={self.col_id: value}))
    def test_trailing_stop_order_handler(self):
        handler = TrailingStopOrderHandler(self.config)

        bar1 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=16, high=18, low=15, close=17, vol=1000)
        bar2 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=17, high=19, low=16, close=18, vol=1000)
        bar3 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=18, high=20, low=17, close=19, vol=1000)
        bar4 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=19, high=21, low=18, close=20, vol=1000)
        bar5 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=20, high=22, low=19, close=21, vol=1000)

        # BUY with bar
        order1 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="1", inst_id="1", action=Buy,
                                                      type=TrailingStop,
                                                      qty=1000,
                                                      stop_price=5)

        self.assertEquals(0, handler.trailing_stop_exec_price(order1.cl_id, order1.cl_ord_id))

        fill_info = handler.process(order1, bar2)
        self.assertEquals(21, handler.trailing_stop_exec_price(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order1, bar3)
        self.assertEquals(21, handler.trailing_stop_exec_price(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order1, bar1)
        self.assertEquals(20, handler.trailing_stop_exec_price(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order1, bar3)
        self.assertEquals(20, handler.trailing_stop_exec_price(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(20, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # BUY
        order2 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="2", inst_id="1", action=Buy,
                                                      type=TrailingStop,
                                                      qty=1000,
                                                      stop_price=5)

        self.assertEquals(0, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))

        fill_info = handler.process_w_price_qty(order2, 16, 1000)
        self.assertEquals(21, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order2, 17, 1000)
        self.assertEquals(21, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order2, 15, 1000)
        self.assertEquals(20, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order2, 19, 1000)
        self.assertEquals(20, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order2, 20, 1000)
        self.assertEquals(20, handler.trailing_stop_exec_price(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(20, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # SELL with bar
        order3 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="3", inst_id="1",
                                                      action=Sell,
                                                      type=TrailingStop, qty=1000,
                                                      stop_price=5)

        self.assertEquals(0, handler.trailing_stop_exec_price(order3.cl_id, order3.cl_ord_id))

        fill_info = handler.process(order3, bar4)
        self.assertEquals(16, handler.trailing_stop_exec_price(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order3, bar3)
        self.assertEquals(16, handler.trailing_stop_exec_price(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order3, bar5)
        self.assertEquals(17, handler.trailing_stop_exec_price(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order3, bar3)
        self.assertEquals(17, handler.trailing_stop_exec_price(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(17, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # SELL
        order4 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="4", inst_id="1",
                                                      action=Sell,
                                                      type=TrailingStop, qty=1000,
                                                      stop_price=5)

        self.assertEquals(0, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))

        fill_info = handler.process_w_price_qty(order4, 21, 1000)
        self.assertEquals(16, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order4, 20, 1000)
        self.assertEquals(16, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order4, 22, 1000)
        self.assertEquals(17, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order4, 18, 1000)
        self.assertEquals(17, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order4, 17, 1000)
        self.assertEquals(17, handler.trailing_stop_exec_price(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(17, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)
Example #15
0
 def test_simulation_clock_current_date_time_with_trade(self):
     timestamp = ClockTest.ts + 10
     trade = ModelFactory.build_trade(inst_id="test", timestamp=timestamp)
     self.simluation_clock.on_trade(trade)
     self.assertEquals(timestamp, self.simluation_clock.now())
Example #16
0
def load_exch_from_row(data_store, row):
    exch = ModelFactory.build_exchange(exch_id=row['exch_id'],
                                       name=row['name'])
    data_store.save_exchange(exch)
    def test_StopLimit_order_handler(self):
        handler = StopLimitOrderHandler(self.config)

        bar1 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=20, high=21, low=19, close=20.5, vol=1000)
        bar2 = ModelFactory.build_bar(timestamp=0, inst_id="1", open=16, high=18, low=15, close=17, vol=1000)

        # BUY
        order1 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="1", inst_id="1", action=Buy,
                                                      type=StopLimit,
                                                      qty=1000,
                                                      limit_price=18,
                                                      stop_price=18.5)
        fill_info = handler.process_w_price_qty(order1, 18, 1000)
        self.assertFalse(handler.stop_limit_ready(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order1, 19, 1000)
        self.assertTrue(handler.stop_limit_ready(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order1, 18, 1000)
        self.assertTrue(handler.stop_limit_ready(order1.cl_id, order1.cl_ord_id))
        self.assertEquals(18, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # BUY with bar
        order2 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="2", inst_id="1", action=Buy,
                                                      type=StopLimit,
                                                      qty=1000,
                                                      limit_price=18,
                                                      stop_price=18.5)
        fill_info = handler.process(order2, bar2)
        self.assertFalse(handler.stop_limit_ready(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order2, bar1)
        self.assertTrue(handler.stop_limit_ready(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order2, bar2)
        self.assertTrue(handler.stop_limit_ready(order2.cl_id, order2.cl_ord_id))
        self.assertEquals(18, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # SELL
        order3 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="3", inst_id="1",
                                                      action=Sell, type=StopLimit,
                                                      qty=1000,
                                                      limit_price=20,
                                                      stop_price=18.5)
        fill_info = handler.process_w_price_qty(order3, 19, 1000)
        self.assertFalse(handler.stop_limit_ready(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order3, 18, 1000)
        self.assertTrue(handler.stop_limit_ready(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process_w_price_qty(order3, 20, 1000)
        self.assertTrue(handler.stop_limit_ready(order3.cl_id, order3.cl_ord_id))
        self.assertEquals(20, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)

        # SELL with bar
        order4 = ModelFactory.build_new_order_request(timestamp=0, cl_id='test', cl_ord_id="4", inst_id="1",
                                                      action=Sell, type=StopLimit,
                                                      qty=1000,
                                                      limit_price=20,
                                                      stop_price=18.5)
        fill_info = handler.process(order4, bar1)
        self.assertFalse(handler.stop_limit_ready(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order4, bar2)
        self.assertTrue(handler.stop_limit_ready(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(None, fill_info)

        fill_info = handler.process(order4, bar1)
        self.assertTrue(handler.stop_limit_ready(order4.cl_id, order4.cl_ord_id))
        self.assertEquals(20, fill_info.fill_price)
        self.assertEquals(1000, fill_info.fill_qty)
Example #18
0
 def sample_country(self):
     country = ModelFactory.build_country('US', 'United States of America',
                                          'US_holiday')
     return country
Example #19
0
def load_ccy_from_row(data_store, row):
    ccy = ModelFactory.build_currency(ccy_id=row['ccy_id'], name=row['name'])
    data_store.save_currency(ccy)
Example #20
0
    def sample_strategy_state(self):
        strategy = ModelFactory.build_strategy_state("BLSH", "test")

        self.add_sample_position(strategy)
        return strategy
Example #21
0
 def sample_portfolio_state(self):
     portfolio = ModelFactory.build_portfolio_state("test_portf", cash=1000)
     self.add_sample_position(portfolio)
     return portfolio
Example #22
0
 def on_acc_upd(self, account_update: AccountUpdate) -> None:
     for update_value in account_update.values.values():
         ModelFactory.update_account_value(
             self.state.values[update_value.key], update_value.key,
             update_value.ccy_values)
Example #23
0
 def sample_sequence(self):
     seq = ModelFactory.build_sequence("test_seq", 999)
     return seq
Example #24
0
 def sample_exchange(self):
     exchange = ModelFactory.build_exchange(
         'SEHK', 'The Stock Exchange of Hong Kong Limited', 'HK', 'HKEX',
         'HK_Holiday')
     return exchange
Example #25
0
 def __remove_order(self, new_ord_req):
     if new_ord_req.inst_id in self.ord_req_map:
         ord_reqs = self.ord_req_map[new_ord_req.inst_id]
         cl_ord_id = ModelFactory.build_cl_ord_id(new_ord_req.cl_id, new_ord_req.cl_ord_id)
         if cl_ord_id in ord_reqs:
             del ord_reqs[cl_ord_id]
Example #26
0
 def sample_timezone(self):
     timezone = ModelFactory.build_timezone("Venezuela Standard Time")
     return timezone
 def add(self, timestamp, data: Dict):
     self.time_list.append(timestamp)
     for col_id, value in data.items():
         self.col_dict[col_id].add(timestamp=timestamp, value=value)
     self.subject.on_next(
         ModelFactory.build_time_series_update_event(source=self.df_id, timestamp=timestamp, data=data))
Example #28
0
 def add_sample_order_position(self, position):
     ModelFactory.add_order_position(position, "BLSH", "O1", 100, 20)
     ModelFactory.add_order_position(position, "BLSH", "O2", 100, 50)
Example #29
0
 def __init__(self, stg_id: str, stg_cls: str, state: StrategyState = None):
     self.stg_id = stg_id
     self.state = state if state else ModelFactory.build_strategy_state(
         stg_id=stg_id, stg_cls=stg_cls)
     self.store = None
     super().__init__(self.state)
Example #30
0
 def sample_currency(self):
     currency = ModelFactory.build_currency('HKD', 'Hong Kong Doller')
     return currency