Exemple #1
0
 def execute_order(self, event):
     # mock a fill at current bid ask
     if event.side == 'buy':
         fill = FillEvent(time.time(), event.instrument,
                             'buy', event.units,
                             '', self.ask,
                             0)
     else:
         fill = FillEvent(time.time(), event.instrument,
                          'sell', event.units,
                          '', self.bid,
                          0)
     return fill
Exemple #2
0
    def execute_order(self, event):

        if event.type == 'ORDER':
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                   'ARCA', event.quantity, event.direction,
                                   None)
            self.events.put(fill_event)
Exemple #3
0
    def stream_to_queue(self):
        response = self.connect_to_stream()
        if response.status_code != 200:
            return
        for line in response.iter_lines(1):
            if line:
                try:
                    dline = line.decode('utf-8')
                    msg = json.loads(dline)
                except Exception as e:
                    self.logger.error(
                        "Caught exception when converting message into json: %s"
                        % str(e))
                    return
                if msg['type'] == 'order_fill':
                    self.logger.debug(msg)

                    timestamp = msg['time']
                    ticker = msg['instrument']
                    side = msg['side']
                    quantity = msg['units']
                    price = msg['price']
                    # commission
                    # Create fill event
                    fev = FillEvent(timestamp, ticker, side, quantity, price)
                    self.events_queue.put(fev)
    def _cross(self, order, last_bar, curr_bar):
        traded = False
        if order.direction == LONG:
            if order.open_or_close == OPEN:
                if order.price >= curr_bar.low_ask_price1 and curr_bar.low_ask_price1 > 0 and order.price < last_bar.close_ask_price1:
                    # cannot buy at limit up
                    # 下降趋势
                    traded = True
            elif order.open_or_close == CLOSE:
                if order.price >= curr_bar.low_ask_price1 and order.price <= curr_bar.high_ask_price1:
                    traded = True
        elif order.direction == SHORT:
            if order.open_or_close == OPEN:
                if order.price <= curr_bar.high_bid_price1 and order.price > last_bar.close_bid_price1:
                    # 上升趋势
                    traded = True
            elif order.open_or_close == CLOSE:
                if order.price >= curr_bar.low_bid_price1 and order.price <= curr_bar.high_bid_price1:
                    traded = True

        if traded:
            return FillEvent(
                symbol=order.symbol,
                datetime=curr_bar.datetime,
                price=order.price,
                quantity=order.quantity,
                direction=order.direction,
                open_or_close=order.open_or_close,
                trade_id=order.trade_id,
            )

        return None
Exemple #5
0
 def execute_order(self, event):
     # converts Order objects into Fill objects
     if event.type == 'ORDER':
         fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                'ARCA',  # ARCA is the exchange we get the data from
                                event.quantity, event.direction, None)
         self.events.put(fill_event)
Exemple #6
0
    def create_fill(self, msg):
        """
        Handles the creation of the FillEvent that will be
        placed onto the events queue subsequent to an order
        being filled.
        """
        fd = self.fill_dict[msg.orderId]

        # Prepare the fill data
        symbol = fd["symbol"]
        exchange = fd["exchange"]
        filled = msg.filled
        direction = fd["direction"]
        fill_cost = msg.avgFillPrice

        # Create a fill event object
        fill = FillEvent(dt.utcnow(), symbol, exchange, filled, direction,
                         fill_cost)

        # Make sure that multiple messages don't create
        # additional fills.
        self.fill_dict[msg.orderId]["filled"] = True

        # Place the fill event onto the event queue
        self.events.put(fill_event)
Exemple #7
0
 def execute_order(self, event):
     if event.type == 'ORDER':
         if self.verbose:
             print("Order Executed:", event.symbol, event.quantity,
                   event.direction)
         fill_event = FillEvent(datetime.utcnow(), event.symbol, 'ARCA',
                                event.quantity, event.direction, 0)
         self.events.put(fill_event)
 def send_order(self, order, send_time):
     reach_time = send_time + self.calculate_latency(order, send_time)
     sign = [1, -1][order.direction == "SELL"]
     quantity = sign * self.calculate_fill_quantity(order, reach_time)
     cost = sign * self.calculate_fill_cost(order, reach_time)
     # will need to figure out how the fills and orders work for each exchange
     fe = FillEvent(reach_time, order.symbol, order.exchange,
                    order.order_type, quantity, cost)
     self.queue.put(fe)
Exemple #9
0
 def test_order_recording(port):
     print(port.current_orders)
     o0 = Order(sym, "BitMEX", "LMT", "SELL", 10, 7300)
     o1 = Order(sym, "BitMEX", "LMT", "SELL", 15, 7300)
     o2 = Order(sym, "BitMEX", "LMT", "SELL", 15, 7301)
     port.record_order(o0, pd.Timestamp.utcnow())
     port.record_order(o1, pd.Timestamp.utcnow())
     port.record_order(o2, pd.Timestamp.utcnow())
     print(port.current_orders)
     f0 = FillEvent(pd.Timestamp.utcnow(), sym, "BitMEX", "MKT", 5, 7300)
     f1 = FillEvent(pd.Timestamp.utcnow(), sym, "BitMEX", "MKT", 10, 7300)
     f2 = FillEvent(pd.Timestamp.utcnow(), sym, "BitMEX", "MKT", 10, 7300)
     port.update_fill(f0)
     print(port.current_orders)
     port.update_fill(f1)
     print(port.current_orders)
     port.update_fill(f2)
     print(port.current_orders)
Exemple #10
0
 def execute_order(self, event):
     """
     简单的讲订单对象自动转化为成交对象,不考虑时延,滑价以及成交
     比率的影响
     """
     if event.type == 'ORDER':
         fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                'ARCA', event.quantity, event.direction,
                                None)
         self.events.put(fill_event)
Exemple #11
0
 def _cross(self, order, last_bar, curr_bar):
     return FillEvent(
         symbol=order.symbol,
         datetime=curr_bar.datetime,
         price=order.price,
         quantity=order.quantity,
         direction=order.direction,
         open_or_close=order.open_or_close,
         trade_id=order.trade_id,
     )
Exemple #12
0
 def execute_order(self, event):
     """ Simply converts Order objects into Fill objects naively,
     i.e. without any latency, slippage or fill ratio problems.
     :param event:Contains an Event object with order information.
     :return:
     """
     if event.type == 'ORDER':
         fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                'ARCA', event.quantity, event.direction,
                                None)
         self.events.put(fill_event)
Exemple #13
0
 def execute_order(self, event):
     """
         for testing there is no slipage or fees to start
     """
     fill = FillEvent(
         symbol=event.symbol,
         quantity=event.quantity,
         direction=event.direction,
         fill_cost=None,
     )
     self.events.put(fill)
Exemple #14
0
 def execute_order(self, event):
     """
     Parametri:
     event - Contiene un oggetto Event con le informazioni dell'ordine.
     """
     if event.type == 'ORDER':
         fill_event = FillEvent(
             datetime.datetime.utcnow(), event.symbol,
             'OANDA', event.quantity, event.direction, None, event.commission
         )
         self.events.put(fill_event)
Exemple #15
0
 def execute_order(self,event):
     """
     简单地将order转换为fill
     没有考虑任何其他因素,滑点,以及交易费用
     timeindex,symbol,exchange,quantity,direction,fill_cost,comission=None
     """
     if event.type=="ORDER":
         fill_event=FillEvent(datetime.datetime.utcnow(),event.symbol,'ARCA',
                              event.quantity,event.direction,0,0)
         print("execution.py put FILL")
         self.events.put(fill_event)
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively

        :param event: Event; OrderEvent.
        """
        if event.type == 'ORDER':
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                   'ARCA', event.quantity, event.direction,
                                   None)
            self.events.put(fill_event)
    def execute_order(self, event):
        """
        Просто наивно конвертирует объекты Order в объекты Fill, то есть не учитывается задержка, проскальзывание или количество акций в приказе, которые можно купить/продать по заданной цене.

        Параметры:
        event - Содержит объект Event с информацией о приказе.
        """
        if event.type == 'ORDER':
            fill_event = FillEvent(event.timeindex, event.symbol,
                                   'ARCA', event.quantity, event.direction, None)
            self.events.put(fill_event)
Exemple #18
0
    def execute_order(self, event):
        """
		Simply converts all order objects into fill objects without consideration of : latency, slippage, and fill-ratio issues

		:param event -  Order event object
		:return:
		"""
        if event.type == 'ORDER':
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                   'ARCA', event.quantity, event.direction,
                                   None)
            self.events.put(fill_event)
Exemple #19
0
    def execute_order(self, event):
        """
        
        """

        if event.type == 'ORDER':
            #event.print_order()
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                   'ARCA', event.quantity, event.direction,
                                   event.quantity * 6.8, event.price, None)

            self.event.put(fill_event)
Exemple #20
0
    def generate_fill_event(self, order):
        """
        Acts on an OrderEvent to generate new FillEvent.
        """
        timeindex = order.datetime
        symbol = order.symbol
        quantity = order.quantity
        direction = order.direction
        price = order.price

        fill = FillEvent(timeindex, symbol, quantity, direction, price)

        return fill
Exemple #21
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            print event.print_order()
            fill_event = FillEvent(event.bar[0], event.symbol,
                                   event.exchange, event.quantity, event.direction, event.quantity * event.bar[6], commission=10)
            self.events.put(fill_event)
Exemple #22
0
 def execute_order(self, event):
     """
     Convert Order objects into Fill objects
     
     Parameter:
     event - Event object with order information
     
     * Using ARCA as the exchange here as a place holder
     """
     if event.type == 'ORDER':
         fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                'ARCA', event.quantity, event.direction, event.position_change, 
                               None)
         self.events.put(fill_event)
Exemple #23
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            fill_event = FillEvent(
                self.bars.get_latest_bars(event.symbol)[0][1], event.symbol,
                'OKEx', event.quantity, event.direction,
                self.bars.get_latest_bars(event.symbol)[0][5])
            self.events.put(fill_event)
Exemple #24
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            #(self, timeindex, symbol, order_type, quantity,price, direction)
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                    event.order_type,event.quantity,event.price,event.direction)
            
            self.events.put(fill_event)        
    def test_convert_fill_to_portfolio_update_basic_check(self):
        """
        Test the "_convert_fill_to_portfolio_update" method
        as a basic sanity check.
        """
        fill_event_buy = FillEvent(datetime.datetime.utcnow(), "MSFT", "BOT",
                                   100, "ARCA", Decimal("50.25"),
                                   Decimal("1.00"))
        self.portfolio_handler._convert_fill_to_portfolio_update(
            fill_event_buy)

        # Check the Portfolio values within the PortfolioHandler
        port = self.portfolio_handler.portfolio
        self.assertEqual(port.cur_cash, Decimal("494974.00"))
Exemple #26
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects in a naive manner (no
        market movement/slippage risk, fill ratio, or other execution
        commonalities).

        Parameters:
            event - Contains an Event object with order information
        """

        if event.type == 'ORDER':
            fill_event = FillEvent(dt.datetime.utcnow(), event.symbol, 'ARCA',
                                   event.quantity, event.direction, None)
            self.events.put(fill_event)
 def execute_order(self, event):
     """
     简易成交
     Parameters:
     event - Contains an Event object with order information.
     """
     if event.type == 'ORDER':
         fill_event = FillEvent(datetime.datetime.utcnow(),
                                event.symbol,
                                '某交易所',
                                event.quantity,
                                event.direction,
                                None,
                                commission=1.5)
         self.events.put(fill_event)
Exemple #28
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            # TODO: rewrite the fill_cost option
            fill_event = FillEvent(datetime.datetime.utcnow(),
                                       event.symbol,
                                       'ARCA', event.quantity,
                                       event.direction) # fill_cost=0, commission=None
            self.events.put(fill_event)
Exemple #29
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        #TODO: add event.type Order target price reached
        # below simply suppose order filled on recevicing order event
        if event.type == 'ORDER':
            fill_event = FillEvent(event.datetime, event.symbol, 'SHSZ',
                                   event.quantity, event.direction,
                                   event.price)
            self.events.put(fill_event)
Exemple #30
0
    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naitvely, i.e., without any latency, slippage or fill ratio problems.

        Parameters:
            event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            fill_event = FillEvent(timeindex=dt.datetime.utcnow(),
                                   symbol=event.symbol,
                                   exchange='N/A',
                                   quantity=event.quantity,
                                   direction=event.direction,
                                   fill_cost=None,
                                   commission=None)
            self.event_queue.put(fill_event)