Example #1
0
 def place_order(self, security, action, price, size, algo="", algo_param={}, userdata=""):
     if size <= 0:
         print("Invalid size {}".format(size))
         return
 
     # Generate Task
     order = Order.new_order(security, action, price, size, self.ctx.trade_date, self.ctx.time,
                             order_type=common.ORDER_TYPE.LIMIT)
 
     task_id = self._get_next_task_id()
     order.task_id = task_id
 
     task = Task(task_id,
                 algo=algo, algo_param=algo_param, data=order,
                 function_name='place_order', trade_date=self.ctx.trade_date)
     # task.task_no = task_id
 
     # Send Order to Exchange
     entrust_no = self._simulator.add_order(order)
     task.data.entrust_no = entrust_no
 
     self.ctx.pm.add_task(task)
     self.entrust_no_task_id_map[entrust_no] = task.task_id
 
     order_status_ind = OrderStatusInd(order)
     order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED
     self._order_status_callback(order_status_ind)
 
     return task_id, ""
Example #2
0
 def place_order(self, security, action, price, size, algo="", algo_param={}, userdata=""):
     if size <= 0:
         print("Invalid size {}".format(size))
         return
 
     # Generate Task
     order = Order.new_order(security, action, price, size, self.ctx.trade_date, self.ctx.time,
                             order_type=common.ORDER_TYPE.LIMIT)
 
     task_id = self._get_next_task_id()
     order.task_id = task_id
 
     task = Task(task_id,
                 algo=algo, algo_param=algo_param, data=order,
                 function_name='place_order', trade_date=self.ctx.trade_date)
     # task.task_no = task_id
 
     # Send Order to Exchange
     entrust_no = self._simulator.add_order(order)
     task.data.entrust_no = entrust_no
 
     self.ctx.pm.add_task(task)
     self.entrust_no_task_id_map[entrust_no] = task.task_id
 
     order_status_ind = OrderStatusInd(order)
     order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED
     self._order_status_callback(order_status_ind)
 
     return task_id, ""
Example #3
0
    def place_order(self,
                    security,
                    action,
                    price,
                    size,
                    algo="",
                    algo_param={},
                    userdata=""):
        if size <= 0:
            print("Invalid size {}".format(size))
            return

        # Generate Order
        if algo == 'vwap':
            order_type = common.ORDER_TYPE.VWAP
        else:
            order_type = common.ORDER_TYPE.LIMIT
        order = Order.new_order(security,
                                action,
                                price,
                                size,
                                self.ctx.trade_date,
                                self.ctx.time,
                                order_type=order_type)

        # Generate Task
        task_id = self._get_next_task_id()
        order.task_id = task_id

        task = Task(task_id,
                    algo=algo,
                    algo_param=algo_param,
                    data=order,
                    function_name='place_order',
                    trade_date=self.ctx.trade_date)
        # task.task_no = task_id

        # Send Order to Exchange
        entrust_no = self._orderbook.add_order(order)
        task.data.entrust_no = entrust_no

        self.ctx.pm.add_task(task)
        self.entrust_no_task_id_map[entrust_no] = task.task_id

        order_status_ind = OrderStatusInd(order)
        order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED
        # order_status_ind.task_no = task_id
        self._order_status_callback(order_status_ind)
        '''
        # TODO: not necessary
        rsp = OrderRsp(entrust_no=entrust_no, task_id=task_id, msg="")
        self.ctx.instance.strategy.on_order_rsp(rsp)
        '''

        return task_id, ""
Example #4
0
    def goal_portfolio(self, positions, algo="", algo_param={}, userdata=""):
        # Generate Orders
        task_id = self._get_next_task_id()

        orders = {}
        for goal in positions:
            sec, goal_size = goal['symbol'], goal['size']
            if sec in self.ctx.pm.holding_securities:
                current_size = self.ctx.pm.get_position(sec).current_size
            else:
                current_size = 0
            diff_size = goal_size - current_size
            if diff_size != 0:
                action = common.ORDER_ACTION.BUY if diff_size > 0 else common.ORDER_ACTION.SELL

                order = FixedPriceTypeOrder.new_order(sec, action, 0.0,
                                                      abs(diff_size),
                                                      self.ctx.trade_date, 0)
                if algo == 'vwap':
                    order.price_target = 'vwap'  # TODO
                elif algo.startswith('limit:'):
                    order.price_target = algo.split(':')[1].strip()
                elif algo == '':
                    order.price_target = 'vwap'
                else:
                    raise NotImplementedError(
                        "goal_portfolio algo = {}".format(algo))

                order.task_id = task_id
                order.entrust_no = self._simulator.add_order(order)
                orders[order.entrust_no] = order

        # Generate Task
        task = Task(task_id,
                    algo=algo,
                    algo_param=algo_param,
                    data=orders,
                    function_name='goal_portfolio',
                    trade_date=self.ctx.trade_date)

        self.ctx.pm.add_task(task)

        # Send Orders to Exchange
        for entrust_no, order in orders.items():
            self.entrust_no_task_id_map[entrust_no] = task.task_id

            order_status_ind = OrderStatusInd(order)
            order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED

            self._order_status_callback(order_status_ind)
Example #5
0
def test_order_trade_task():
    from jaqs.data.basic import TradeStat, Trade, Task, TaskInd, Order, OrderStatusInd

    order = Order()
    order.symbol = 'SPY'
    order.task_id = 10000001
    order.entrust_no = '123'

    order.entrust_size = 10
    order.entrust_action = 'Short'
    order.entrust_price = 1.2
    order.entrust_time = 95055
    order.entrust_date = 20171201

    order.fill_price = 1.19
    order.fill_size = 3
    order.commission = 0.001

    str(order)

    o2 = Order(order)
    o2.entrust_no = '124'

    o3 = Order.new_order('SPY', 'Buy', 10, 10, 20111111, 143029, 'Limit')

    oind = OrderStatusInd(order)
    OrderStatusInd.create_from_dict({'symbol': 'SPY'})
    str(oind)

    task = Task(order.task_id, 'vwap', {'a': 'b'}, order, 'place_order',
                order.entrust_date)
    assert (not task.is_finished)
    task.task_status = common.TASK_STATUS.DONE
    assert task.is_finished

    tind = TaskInd(task.task_id, task.task_status, task.algo, 'success')
    str(tind)

    tind2 = TaskInd.create_from_dict({'task_id': 2011223})

    trade = Trade(order)
    trade.set_fill_info(15, 20, 20171202, 112311, 12345)
    str(trade)

    t2 = Trade.create_from_dict({'symbol': 'SPY'})

    tstat = TradeStat()
    str(tstat)
Example #6
0
    def cancel_order(self, entrust_no):
        """
        Cancel an order.

        Parameters
        ----------
        entrust_no : str

        Returns
        -------
        err_msg : str
            default ""

        """
        order = self.__orders.pop(entrust_no, None)
        if order is None:
            err_msg = "No order with entrust_no {} in simulator.".format(
                entrust_no)
            order_status_ind = None
        else:
            order.cancel_size = order.entrust_size - order.fill_size
            order.order_status = common.ORDER_STATUS.CANCELLED

            err_msg = ""
            order_status_ind = OrderStatusInd(order)
        return order_status_ind, err_msg
Example #7
0
    def cancel_order(self, entrust_no):
        order = self.orders.pop(entrust_no)
        order.cancel_size = order.entrust_size - order.fill_size
        order.order_status = common.ORDER_STATUS.CANCELLED

        order_status_ind = OrderStatusInd(order)
        '''
        for i in xrange(len(self.orders)):
            order = self.orders[i]
            
            if (order.is_finished):
                continue
            
            if (order.entrust_no == entrust_no):
                order.cancel_size = order.entrust_size - order.fill_size
                order.order_status = common.ORDER_STATUS.CANCELLED
            
            # todo
            orderstatus = OrderStatusInd()
            orderstatus.init_from_order(order)
            
            return orderstatus
    
        '''
        return order_status_ind
Example #8
0
def test_order_trade_task():
    from jaqs.data.basic import TradeStat, Trade, Task, TaskInd, Order, OrderStatusInd
    
    order = Order()
    order.symbol = 'SPY'
    order.task_id = 10000001
    order.entrust_no = '123'
    
    order.entrust_size = 10
    order.entrust_action = 'Short'
    order.entrust_price = 1.2
    order.entrust_time = 95055
    order.entrust_date = 20171201
    
    order.fill_price = 1.19
    order.fill_size = 3
    order.commission = 0.001
    
    str(order)
    
    o2 = Order(order)
    o2.entrust_no = '124'
    
    o3 = Order.new_order('SPY', 'Buy', 10, 10, 20111111, 143029, 'Limit')
    
    oind = OrderStatusInd(order)
    OrderStatusInd.create_from_dict({'symbol': 'SPY'})
    str(oind)
    
    task = Task(order.task_id, 'vwap', {'a': 'b'}, order, 'place_order', order.entrust_date)
    assert (not task.is_finished)
    task.task_status = common.TASK_STATUS.DONE
    assert task.is_finished
    
    tind = TaskInd(task.task_id, task.task_status, task.algo, 'success')
    str(tind)
    
    tind2 = TaskInd.create_from_dict({'task_id': 2011223})
    
    trade = Trade(order)
    trade.set_fill_info(15, 20, 20171202, 112311, 12345)
    str(trade)
    
    t2 = Trade.create_from_dict({'symbol': 'SPY'})
    
    tstat = TradeStat()
    str(tstat)
Example #9
0
    def cancel_order(self, task_id):
        task = self.ctx.pm.get_task(task_id)
        if task.function_name == 'place_order':
            order = task.data
            if order.order_status in [common.ORDER_STATUS.NEW, common.ORDER_STATUS.ACCEPTED]:
                entrust_no = order.entrust_no
                order_status_ind = self._orderbook.cancel_order(entrust_no)
                task_id = self.entrust_no_task_id_map[entrust_no]
                order_status_ind.task_id = task_id
                # order_status_ind.task_no = task_id
                self._order_status_callback(order_status_ind)
            else:
                order_status_ind = OrderStatusInd(order)
                order_status_ind.task_id = task_id
                self._order_status_callback(order_status_ind)

        else:
            raise NotImplementedError("cancel task with function_name = {}".format(task.function_name))
Example #10
0
    def goal_portfolio(self, positions, algo="", algo_param={}, userdata=""):
        # Generate Orders
        task_id = self._get_next_task_id()
        
        orders = []
        for goal in positions:
            sec, goal_size = goal['symbol'], goal['size']
            if sec in self.ctx.pm.holding_securities:
                current_size = self.ctx.pm.get_position(sec).current_size
            else:
                current_size = 0
            diff_size = goal_size - current_size
            if diff_size != 0:
                action = common.ORDER_ACTION.BUY if diff_size > 0 else common.ORDER_ACTION.SELL
        
                order = FixedPriceTypeOrder.new_order(sec, action, 0.0, abs(diff_size), self.ctx.trade_date, 0)
                if algo == 'vwap':
                    order.price_target = 'vwap'  # TODO
                elif algo == '':
                    order.price_target = 'vwap'
                else:
                    raise NotImplementedError("goal_portfolio algo = {}".format(algo))

                order.task_id = task_id
                orders.append(order)

        # Generate Task
        task = Task(task_id,
                    algo=algo, algo_param=algo_param, data=orders,
                    function_name='goal_portfolio', trade_date=self.ctx.trade_date)

        self.ctx.pm.add_task(task)

        # Send Orders to Exchange
        for order in orders:
            entrust_no = self._simulator.add_order(order)
            # task.data.entrust_no = entrust_no
            self.entrust_no_task_id_map[entrust_no] = task.task_id
            
            order_status_ind = OrderStatusInd(order)
            order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED
            self._order_status_callback(order_status_ind)
Example #11
0
    def place_order(self, security, action, price, size, algo="", algo_param={}, userdata=""):
        if size <= 0:
            print("Invalid size {}".format(size))
            return
        
        # Generate Order
        if algo == 'vwap':
            order_type = common.ORDER_TYPE.VWAP
        else:
            order_type = common.ORDER_TYPE.LIMIT
        order = Order.new_order(security, action, price, size, self.ctx.trade_date, self.ctx.time,
                                order_type=order_type)

        # Generate Task
        task_id = self._get_next_task_id()
        order.task_id = task_id
        
        task = Task(task_id,
                    algo=algo, algo_param=algo_param, data=order,
                    function_name='place_order', trade_date=self.ctx.trade_date)
        # task.task_no = task_id
        
        # Send Order to Exchange
        entrust_no = self._orderbook.add_order(order)
        task.data.entrust_no = entrust_no
        
        self.ctx.pm.add_task(task)
        self.entrust_no_task_id_map[entrust_no] = task.task_id

        order_status_ind = OrderStatusInd(order)
        order_status_ind.order_status = common.ORDER_STATUS.ACCEPTED
        # order_status_ind.task_no = task_id
        self._order_status_callback(order_status_ind)


        '''
        # TODO: not necessary
        rsp = OrderRsp(entrust_no=entrust_no, task_id=task_id, msg="")
        self.ctx.instance.strategy.on_order_rsp(rsp)
        '''
        
        return task_id, ""
Example #12
0
    def match(self, price_dic, date=19700101, time=150000):
        self._validate_price(price_dic)

        results = []
        for order in self.__orders.values():
            symbol = order.symbol
            symbol_dic = price_dic[symbol]

            # get fill price
            if isinstance(order, FixedPriceTypeOrder):
                price_target = order.price_target
                fill_price = symbol_dic[price_target]
            elif isinstance(order, VwapOrder):
                if order.start != -1:
                    raise NotImplementedError("Vwap of a certain time range")
                fill_price = symbol_dic['vwap']
            elif isinstance(order, Order):
                # TODO
                fill_price = symbol_dic['close']
            else:
                raise NotImplementedError("order class {} not support!".format(
                    order.__class__))

            # get fill size
            fill_size = order.entrust_size - order.fill_size

            # create trade indication
            trade_ind = Trade(order)
            trade_ind.set_fill_info(fill_price,
                                    fill_size,
                                    date,
                                    time,
                                    self._next_fill_no(),
                                    trade_date=date)

            # update order status
            order.fill_price = (order.fill_price * order.fill_size +
                                fill_price * fill_size) / (order.fill_size +
                                                           fill_size)
            order.fill_size += fill_size
            if order.fill_size == order.entrust_size:
                order.order_status = common.ORDER_STATUS.FILLED

            order_status_ind = OrderStatusInd(order)

            results.append((trade_ind, order_status_ind))

        self.__orders = {
            k: v
            for k, v in self.__orders.items() if not v.is_finished
        }
        # self.cancel_order(order.entrust_no)  # TODO DEBUG

        return results
Example #13
0
    def on_order_status(self, ind_dic):
        """
        
        Parameters
        ----------
        ind_dic : dict

        """
        # print("\nGateway on order status: ")
        # print(ind_dic)
        if 'security' in ind_dic:
            ind_dic['symbol'] = ind_dic.pop('security')

        ind = OrderStatusInd.create_from_dict(ind_dic)

        self.ctx.strategy.on_order_status(ind)
Example #14
0
    def on_order_status(self, ind_dic):
        """
        
        Parameters
        ----------
        ind_dic : dict

        """
        # print("\nGateway on order status: ")
        # print(ind_dic)
        if 'security' in ind_dic:
            ind_dic['symbol'] = ind_dic.pop('security')
        
        ind = OrderStatusInd.create_from_dict(ind_dic)
        
        self.ctx.strategy.on_order_status(ind)
Example #15
0
    def on_order_status(self, ind_dic):
        """
        
        Parameters
        ----------
        ind_dic : dict

        """
        # print("\nGateway on order status: ")
        # print(ind_dic)
        if 'security' in ind_dic:
            ind_dic['symbol'] = ind_dic.pop('security')

        ind = OrderStatusInd.create_from_dict(ind_dic)
        ind.task_no = self._task_no_id_map[ind.task_id]

        e = Event(EVENT_TYPE.ORDER_STATUS_IND)
        e.dic['ind'] = ind
        self.ctx.instance.put(e)
Example #16
0
    def _make_trade_bar(self, quote_dic):

        result = []

        for entrust_no, order in self.orders.items():
            quote = quote_dic[order.symbol]
            low = quote.low
            high = quote.high
            quote_date = quote.trade_date
            quote_time = quote.time
            volume = quote.volume
            '''
            if order.order_type == common.ORDER_TYPE.LIMIT:
                if order.entrust_action == common.ORDER_ACTION.BUY and order.entrust_price >= low:
                    trade = Trade()
                    trade.init_from_order(order)
                    trade.send_fill_info(order.entrust_price, order.entrust_size,
                                         quote_date, quote_time,
                                         self._next_fill_no())
                    
                    order.order_status = common.ORDER_STATUS.FILLED
                    order.fill_size = trade.fill_size
                    order.fill_price = trade.fill_price
                    
                    orderstatus_ind = OrderStatusInd()
                    orderstatus_ind.init_from_order(order)
                    
                    result.append((trade, orderstatus_ind))
                    
                elif order.entrust_action == common.ORDER_ACTION.SELL and order.entrust_price <= high:
                    trade = Trade()
                    trade.init_from_order(order)
                    trade.send_fill_info(order.entrust_price, order.entrust_size,
                                         quote_date, quote_time,
                                         self._next_fill_no())
                    
                    order.order_status = common.ORDER_STATUS.FILLED
                    order.fill_size = trade.fill_size
                    order.fill_price = trade.fill_price
                    
                    orderstatus_ind = OrderStatusInd()
                    orderstatus_ind.init_from_order(order)

                    result.append((trade, orderstatus_ind))
            
            elif order.order_type == common.ORDER_TYPE.STOP:
                if order.entrust_action == common.ORDER_ACTION.BUY and order.entrust_price <= high:
                    trade = Trade()
                    trade.init_from_order(order)
                    trade.send_fill_info(order.entrust_price, order.entrust_size,
                                         quote_date, quote_time,
                                         self._next_fill_no())
                    
                    order.order_status = common.ORDER_STATUS.FILLED
                    order.fill_size = trade.fill_size
                    order.fill_price = trade.fill_price
                    orderstatus_ind = OrderStatusInd()
                    orderstatus_ind.init_from_order(order)
                    result.append((trade, orderstatus_ind))
                
                if order.entrust_action == common.ORDER_ACTION.SELL and order.entrust_price >= low:
                    trade = Trade()
                    trade.init_from_order(order)
                    trade.send_fill_info(order.entrust_price, order.entrust_size,
                                         quote_date, quote_time,
                                         self._next_fill_no())
                    
                    order.order_status = common.ORDER_STATUS.FILLED
                    order.fill_size = trade.fill_size
                    order.fill_price = trade.fill_price
                    orderstatus_ind = OrderStatusInd()
                    orderstatus_ind.init_from_order(order)
                    result.append((trade, orderstatus_ind))
            '''

            entrust_price = order.entrust_price
            entrust_size = order.entrust_size

            fill_size = 0
            if order.order_type == common.ORDER_TYPE.LIMIT:
                if common.ORDER_ACTION.is_positive(
                        order.entrust_action) and entrust_price >= low:
                    fill_price = min(entrust_price, high)
                    # fill_size = min(entrust_size, self.participation_rate * volume)
                    fill_size = entrust_size

                elif common.ORDER_ACTION.is_negative(
                        order.entrust_action) and order.entrust_price <= high:
                    fill_price = max(entrust_price, low)
                    # fill_size = min(entrust_size, self.participation_rate * volume)
                    fill_size = entrust_size

            elif order.order_type == common.ORDER_TYPE.STOP:
                if common.ORDER_ACTION.is_positive(
                        order.entrust_action) and order.entrust_price <= high:
                    fill_price = max(entrust_price, low)
                    # fill_size = min(entrust_size, self.participation_rate * volume)
                    fill_size = entrust_size

                if common.ORDER_ACTION.is_negative(
                        order.entrust_action) and order.entrust_price >= low:
                    fill_price = min(entrust_price, high)
                    # fill_size = min(entrust_size, self.participation_rate * volume)
                    fill_size = entrust_size

            elif order.order_type == common.ORDER_TYPE.VWAP:
                fill_price = quote.vwap
                fill_size = entrust_size

            if not fill_size:
                continue

            trade_ind = Trade(order)
            trade_ind.set_fill_info(order.entrust_price,
                                    order.entrust_size, quote_date, quote_time,
                                    self._next_fill_no())

            order.fill_price = (
                (order.fill_price * order.fill_size + fill_size * fill_price) /
                (order.fill_size + fill_size))
            order.fill_size += fill_size
            if order.fill_size == order.entrust_size:
                order.order_status = common.ORDER_STATUS.FILLED

            order_status_ind = OrderStatusInd(order)

            result.append((trade_ind, order_status_ind))

        self.orders = {
            k: v
            for k, v in self.orders.items() if not v.is_finished
        }

        return result