Example #1
0
 def post(self):
     """发单"""
     args = self.postParser.parse_args()
     token = args['token']
     if token != TOKEN:
         return {'result_code':'error','message':'token error'}
     print(args)
     vtSymbol = args['vtSymbol']        
     price = args['price']        
     volume = args['volume']        
     priceType = args['priceType']        
     direction = args['direction']        
     offset = args['offset']      
     
     contract = me.getContract(vtSymbol)
     if not contract:
         return {'result_code':'error','message':'contract error'}
     
     priceType_map = {'PRICETYPE_LIMITPRICE' : u'限价','PRICETYPE_MARKETPRICE' : u'市价','PRICETYPE_FAK' : u'FAK','PRICETYPE_FOK' : u'FOK'}
     direction_map = {'DIRECTION_LONG' : u'多','DIRECTION_SHORT' : u'空'}
     offset_map    = {'OFFSET_OPEN' : u'开仓',  'OFFSET_CLOSE' : u'平仓','OFFSET_CLOSETODAY' : u'平今','OFFSET_CLOSEYESTERDAY' : u'平昨'}
     
     req = VtOrderReq()
     req.symbol    = contract.symbol
     req.exchange  = contract.exchange
     req.price     = float(price)
     req.volume    = int(volume)
     req.priceType = priceType_map[ priceType ]
     req.direction = direction_map[ direction ]
     req.offset    = offset_map[ offset ]
     vtOrderID     = me.sendOrder(req, contract.gatewayName)
     return {'result_code':'success','data':vtOrderID}
Example #2
0
    def sendOrder(self, algo, vtSymbol, direction, price, volume, 
                  priceType=None, offset=None):
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            self.writeLog(u'%s委托下单失败,找不到合约:%s' %(algo.algoName, vtSymbol))

        req = VtOrderReq()
        req.vtSymbol = vtSymbol
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.direction = direction        
        req.offset = OFFSET_CLOSETODAY
        req.price = price
        req.volume = volume
        
        if priceType:
            req.priceType = priceType
        else:
            req.priceType = PRICETYPE_LIMITPRICE
        
        if offset:
            req.offset = offset
        else:
            req.offset = OFFSET_OPEN
        
        vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)
        self.orderAlgoDict[vtOrderID] = algo
        
        return vtOrderID
Example #3
0
    def create_bulk_orders(self, orders):
        try:

            req = VtOrderReq()
            for order in orders:
                req.symbol = self.symbol
                if order['side'] == 'Buy':
                    req.direction = DIRECTION_LONG
                elif order['side'] == 'Sell':
                    req.direction = DIRECTION_SHORT
                else:
                    logger.error(
                        "Create_bulk_orders: Order direction is worng!")
                req.volume = order['orderQty']
                req.price = order['price']
                req.priceType = PRICETYPE_LIMITPRICE

                if not self.dry_run:
                    if req.direction == DIRECTION_LONG and self.mainengine.dataEngine.positionDict[
                            'eth'].position - self.mainengine.dataEngine.positionDict[
                                'eth'].frozen > settings.ORDER_START_SIZE * float(
                                    self.get_ticker().bidPrice1
                                ) or req.direction == DIRECTION_SHORT and self.mainengine.dataEngine.positionDict[
                                    'ada'].position - self.mainengine.dataEngine.positionDict[
                                        'ada'].frozen > settings.ORDER_START_SIZE:
                        self.mainengine.getGateway(GATEWAY_NAME).sendOrder(req)
                    else:
                        logger.info("no sufficent money!")
            sleep(settings.API_REST_INTERVAL)
            self.mm_debug()

        except Exception, e:
            print e
Example #4
0
    def sendOrder(self, vtSymbol, direction, offset, price, volume, payup=0):
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            return ''

        req = VtOrderReq()
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.vtSymbol = contract.vtSymbol
        req.direction = direction
        req.offset = offset
        req.volume = int(volume)
        req.priceType = PRICETYPE_LIMITPRICE

        if direction == DIRECTION_LONG:
            req.price = price + payup * contract.priceTick
        else:
            req.price = price - payup * contract.priceTick

        # 委托转换
        reqList = self.mainEngine.convertOrderReq(req)
        vtOrderIDList = []

        for req in reqList:
            vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)
            vtOrderIDList.append(vtOrderID)

        return vtOrderIDList
Example #5
0
 def sendOrder(self, vtSymbol, direction, offset, price, volume, payup=0):
     """发单"""
     contract = self.mainEngine.getContract(vtSymbol)
     if not contract:
         return ''
     
     req = VtOrderReq()
     req.symbol = contract.symbol
     req.exchange = contract.exchange
     req.vtSymbol = contract.vtSymbol
     req.direction = direction
     req.offset = offset
     req.volume = int(volume)
     req.priceType = PRICETYPE_LIMITPRICE
     
     if direction == DIRECTION_LONG:
         req.price = price + payup * contract.priceTick
     else:
         req.price = price - payup * contract.priceTick
         
     # 委托转换
     reqList = self.mainEngine.convertOrderReq(req)
     vtOrderIDList = []
     
     for req in reqList:
         vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)
         vtOrderIDList.append(vtOrderID)
     
     return vtOrderIDList
Example #6
0
    def sendOrder(self, orderDoc, callback=None):

        orderReq = VtOrderReq()

        # 按匹配字段赋值
        for key in self.order_map.keys():
            orderReq.__setattr__(key, orderDoc[self.order_map[key]])

        # 查询获得ctp_Code
        orderReq.symbol = self.getCtpCode(orderDoc['code'])
        # 价格类型
        orderReq.priceType = PRICETYPE_MARKETPRICE
        # 买卖方向
        orderReq.direction = DIRECTION_LONG if orderDoc[
            "mode"] == 1 else DIRECTION_SHORT
        # 平仓类型
        orderReq.offset = OFFSET_OPEN if orderDoc[
            "isopen"] == 1 else OFFSET_CLOSE

        vid = self.API.tdApi.sendOrder(orderReq)
        print(orderReq.symbol, vid)
        self.printClass(orderReq)

        if callback is not None:
            self.ee.register(EVENT_TRADE + vid, callback)
            self.ee.register(EVENT_ORDER + vid, callback)
        else:
            self.ee.register(EVENT_TRADE + vid, self.onQryTrade)
            self.ee.register(EVENT_ORDER + vid, self.onQryOrder)
Example #7
0
    def place_order(self, orderInfo):
        global order_time

        try:
            print orderInfo
            #rs = []
            req = VtOrderReq()
            for order in orderInfo:
                req.symbol = order['tickerPair']
                if order['action'] == 'bid':
                    req.direction = DIRECTION_LONG
                else:
                    req.direction = DIRECTION_SHORT
                #req.direction = order['action']
                req.volume = order['amount']
                req.price = order['price']
                req.priceType = PRICETYPE_LIMITPRICE

                #if not self.mock and order_time == 0:
                if not self.mock:
                    self.mainengine.getGateway(GATEWAY_NAME).sendOrder(req)

            #if not self.mock:
            #    responses = self.send_request(rs)
            order_time = 1
            self.hasOpenOrder = True
            self.openOrderCheckCount = 0
        except Exception, e:
            # raise
            print e
Example #8
0
    def onPlaceOrder(self, clientId, req):
        """委托"""
        params = req['params']
        s, e = params['security'].split('.')

        contract = self.mainEngine.getContract(s)

        if not contract:
            vtOrderID = ''
            error = [-1, u'委托失败,找不到合约%s' % params['security']]
        else:
            vor = VtOrderReq()
            vor.symbol = s
            vor.exchange = EXCHANGE_MAP[e]
            vor.direction, vor.offset = ACTION_MAP[params['action']]
            vor.price = float(params['price'])
            vor.volume = int(params['size'])
            vor.priceType = PRICETYPE_LIMITPRICE

            vtOrderID = self.mainEngine.sendOrder(vor, contract.gatewayName)
            error = [0, '']

        self.server.send_rsp(clientId, req, vtOrderID, error)

        self.writeLog(u'发出响应:%s' % vtOrderID)
Example #9
0
    def onPlaceOrder(self, clientId, req):
        """委托"""
        params = req['params']
        s, e = params['security'].split('.')
        
        contract = self.mainEngine.getContract(s)        

        if not contract:
            vtOrderID = ''
            error = [-1, u'委托失败,找不到合约%s' %params['security']]
        else:
            vor = VtOrderReq()
            vor.symbol = s
            vor.exchange = EXCHANGE_MAP[e]
            vor.direction, vor.offset = ACTION_MAP[params['action']]
            vor.price = float(params['price'])
            vor.volume = int(params['size'])
            vor.priceType = PRICETYPE_LIMITPRICE
            
            vtOrderID = self.mainEngine.sendOrder(vor, contract.gatewayName)
            error = [0, '']
        
        self.server.send_rsp(clientId, req, vtOrderID, error)
        
        self.writeLog(u'发出响应:%s' %vtOrderID)
Example #10
0
 def fastTrade(self, symbol, direction, offset, price, volume):
     """封装下单函数"""
     contract = self.mainEngine.getContract(symbol)
     if not contract:
         return
     
     req = VtOrderReq()
     req.symbol = symbol
     req.exchange = contract.exchange
     req.direction = direction
     req.offset = offset
     req.price = price
     req.volume = volume
     req.priceType = PRICETYPE_LIMITPRICE
     self.mainEngine.sendOrder(req, contract.gatewayName)
Example #11
0
    def fastTrade(self, symbol, direction, offset, price, volume):
        """封装下单函数"""
        contract = self.mainEngine.getContract(symbol)
        if not contract:
            return

        req = VtOrderReq()
        req.symbol = symbol
        req.exchange = contract.exchange
        req.direction = direction
        req.offset = offset
        req.price = price
        req.volume = volume
        req.priceType = PRICETYPE_LIMITPRICE
        self.mainEngine.sendOrder(req, contract.gatewayName)
Example #12
0
 def sendOrder(self, vtSymbol, direction, offset, price, volume):
     """发单"""
     contract = self.mainEngine.getContract(vtSymbol)
     if not contract:
         return ''
     
     req = VtOrderReq()
     req.symbol = contract.symbol
     req.exchange = contract.exchange
     req.vtSymbol = vtSymbol
     req.price = price
     req.volume = volume
     req.direction = direction
     req.offset = offset
     req.priceType = PRICETYPE_LIMITPRICE
     
     return self.mainEngine.sendOrder(req, contract.gatewayName)
Example #13
0
    def sendOrder(self, vtSymbol, direction, offset, price, volume):
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            return ''

        req = VtOrderReq()
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.vtSymbol = vtSymbol
        req.price = price
        req.volume = volume
        req.direction = direction
        req.offset = offset
        req.priceType = PRICETYPE_LIMITPRICE

        return self.mainEngine.sendOrder(req, contract.gatewayName)
Example #14
0
    def sendOrder(self, algo, vtSymbol, direction, price, volume):
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            self.writeLog(u'%s委托下单失败,找不到合约:%s' % (algo.algoName, vtSymbol))

        req = VtOrderReq()
        req.vtSymbol = vtSymbol
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.direction = direction
        req.priceType = PRICETYPE_LIMITPRICE
        req.offset = OFFSET_CLOSETODAY
        req.price = price
        req.volume = volume
        vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)

        return vtOrderID
Example #15
0
    def sendOrder(self,
                  algo,
                  vtSymbol,
                  direction,
                  price,
                  volume,
                  priceType=None,
                  offset=None):
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            self.writeLog(u'%s委托下单失败,找不到合约:%s' % (algo.algoName, vtSymbol))

        vtSymbol = '.'.join([contract.symbol, contract.exchange])
        req = VtOrderReq()
        req.vtSymbol = vtSymbol
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.direction = direction
        req.offset = OFFSET_CLOSETODAY
        req.price = price
        req.volume = volume

        if priceType:
            req.priceType = priceType
        else:
            req.priceType = PRICETYPE_LIMITPRICE

        if offset:
            req.offset = offset
        else:
            req.offset = OFFSET_OPEN

        strData = 'symbol %s exchange %s price %.2f volume %d direction %s offset %s vtSymbol %s gatewayName %s'\
        %(req.symbol,req.exchange,req.price,req.volume,req.direction,req.offset,req.vtSymbol,contract.gatewayName)

        print 'currency productClass ', req.currency, req.productClass
        # print 'sendOrder req:'
        # print strData
        vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)
        self.orderAlgoDict[vtOrderID] = algo

        return vtOrderID
Example #16
0
    def grid_place_order(self, order_type, level):

        try:
            #logger.info("grid_place_order level %d, grid[level] %s" % (level, grid[level]))
            if 0 <= level < GRID_LEVELS:
                price = self.grid_price(level)
                #                logger.info("grid_place_order : level %d, price %f, direction %s" % (level, price, order_type))

                if (grid[level] == "" or grid[level] == "-"):

                    req = VtOrderReq()
                    req.symbol = self.exchange.symbol
                    req.volume = TRANCHE_SIZE
                    req.price = price
                    req.priceType = PRICETYPE_LIMITPRICE

                    if order_type == 'buy' and self.exchange.mainengine.dataEngine.positionDict[
                            'btc'].position - self.exchange.mainengine.dataEngine.positionDict[
                                'btc'].frozen > TRANCHE_SIZE * self.basePrice:
                        req.direction = DIRECTION_LONG
                        id = self.exchange.place_order(req)
                    elif order_type == 'sell' and self.exchange.mainengine.dataEngine.positionDict[
                            'eth'].position - self.exchange.mainengine.dataEngine.positionDict[
                                'eth'].frozen > TRANCHE_SIZE:
                        req.direction = DIRECTION_SHORT
                        id = self.exchange.place_order(req)
                    else:
                        id = ""
                        logger.error(
                            "insufficent money!Create_bulk_orders: Order direction is worng!"
                        )
                else:
                    logger.info("placing order on wrong level!")
                    #print out grid
                    self.grid_debug()
                    id = ""
            else:
                id = ""

        except Exception, e:
            id = ""
            print e
Example #17
0
    def sendOrder(self,
                  algo,
                  vtSymbol,
                  direction,
                  price,
                  volume,
                  priceType=None,
                  offset=None):
        logger.info(f"{algo.algoName}")
        print(f"进入发单")
        print(vtSymbol)
        """发单"""
        contract = self.mainEngine.getContract(vtSymbol)
        if not contract:
            self.writeLog(u'%s委托下单失败,找不到合约:%s' % (algo.algoName, vtSymbol))

        req = VtOrderReq()
        req.vtSymbol = vtSymbol
        req.symbol = contract.symbol
        req.exchange = contract.exchange
        req.direction = direction
        req.offset = OFFSET_CLOSETODAY
        req.price = price
        req.volume = volume

        if priceType:
            req.priceType = priceType
        else:
            req.priceType = PRICETYPE_LIMITPRICE

        if offset:
            req.offset = offset
        else:
            req.offset = OFFSET_OPEN

        vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName)
        self.orderAlgoDict[vtOrderID] = algo
        logger.info(f"{vtOrderID}")

        return vtOrderID
Example #18
0
    def sendOrder(self, symbol, orderType, price, volume, strategy):
        try:
            req = VtOrderReq()
            req.symbol = symbol
            req.vtSymbol = symbol
            req.price = price
            req.volume = volume
            req.priceType = PRICETYPE_LIMITPRICE

            gatewayName = "TradeDllAShare"

            # CTA委托类型映射
            if orderType == CTAORDER_BUY:
                req.direction = DIRECTION_LONG
            elif orderType == CTAORDER_SELL:
                req.direction = DIRECTION_SHORT
            else:
                self.writeLog(u"不支持订单方向类型:" + orderType)

            VtOrderID = self.mainEngine.sendOrder(req, gatewayName)

            if VtOrderID:
                # 下单成功,添加orderid和策略对应关系
                # self.orderStrategyDict[VtOrderID] = strategy  # 保存order和策略的映射关系
                # self.strategyDict[strategy.strategyID].addOrder(VtOrderID)  # 添加到策略委托号集合中

                self.writeLog(u'策略%s发送委托成功,%s,%s,%s@%s' %
                              (strategy.strategyID, symbol, req.direction,
                               volume, price))
            else:
                self.writeLog(u"策略%s发送委托失败,%s,%s,%s@%s" %
                              (strategy.strategyID, symbol, req.direction,
                               volume, price))

            return VtOrderID
        except:
            traceback.print_exc()
            return VtOrderID
Example #19
0
    def sendOrder(self, symbol, orderType, price, volume):
        try:
            req = VtOrderReq()
            req.symbol = symbol
            req.vtSymbol = symbol
            req.price = price
            req.volume = volume
            req.priceType = PRICETYPE_LIMITPRICE

            gatewayName = "FUTU"

            req.direction = orderType
            orderID = self.mainEngine.sendOrder(req, gatewayName)

            if orderID:
                self.writeLog(u'委托成功 %s, %s,%s@%s %s' %
                              (symbol, orderType, volume, price, orderID))
            else:
                self.writeLog(u'委托失败 %s, %s,%s@%s %s' %
                              (symbol, orderType, volume, price, orderID))
            return orderID
        except:
            traceback.print_exc()
Example #20
0
    def newOrder(self, vtSymbol):
        """"""
        for vtPositionName in self.targetDict.keys():
            if vtSymbol not in vtPositionName:
                continue

            pos = self.posDict[vtPositionName]
            target = self.targetDict[vtPositionName]
            if pos == target:
                continue

            contract = self.mainEngine.getContract(vtSymbol)
            tick = self.mainEngine.getTick(vtSymbol)
            if not tick:
                return

            req = VtOrderReq()
            req.symbol = contract.symbol
            req.exchange = contract.exchange
            req.priceType = PRICETYPE_LIMITPRICE
            req.volume = abs(target - pos)

            # Open position
            if target > pos:
                req.offset = OFFSET_OPEN

                if DIRECTION_LONG in vtPositionName:
                    req.direction = DIRECTION_LONG
                    if tick.upperLimit:
                        req.price = tick.upperLimit
                    else:
                        req.price = tick.askPrice1
                elif DIRECTION_SHORT in vtPositionName:
                    req.direction = DIRECTION_SHORT
                    if tick.lowerLimit:
                        req.price = tick.lowerLimit
                    else:
                        req.price = tick.bidPrice1

                self.mainEngine.sendOrder(req, contract.gatewayName)

            # Close position
            elif target < pos:
                req.offset = OFFSET_CLOSE

                if DIRECTION_LONG in vtPositionName:
                    req.direction = DIRECTION_SHORT
                    if tick.upperLimit:
                        req.price = tick.upperLimit
                    else:
                        req.price = tick.askPrice1

                elif DIRECTION_SHORT in vtPositionName:
                    req.direction = DIRECTION_LONG
                    if tick.lowerLimit:
                        req.price = tick.lowerLimit
                    else:
                        req.price = tick.bidPrice1

                # Use auto-convert for solving today/yesterday position problem
                reqList = self.mainEngine.convertOrderReq(req)
                for convertedReq in reqList:
                    self.mainEngine.sendOrder(convertedReq,
                                              contract.gatewayName)

            # Write log
            msg = u'发出%s委托 %s%s %s@%s' % (vtSymbol, req.direction, req.offset,
                                          req.price, req.volume)
            self.writeLog(msg)
Example #21
0
 def newOrder(self, vtSymbol):
     """"""
     for vtPositionName in self.targetDict.keys():
         if vtSymbol not in vtPositionName:
             continue
         
         pos = self.posDict[vtPositionName]
         target = self.targetDict[vtPositionName]            
         if pos == target:
             continue
         
         contract = self.mainEngine.getContract(vtSymbol)
         tick = self.mainEngine.getTick(vtSymbol)
         if not tick:
             return
         
         req = VtOrderReq()
         req.symbol = contract.symbol
         req.exchange = contract.exchange
         req.priceType = PRICETYPE_LIMITPRICE            
         req.volume = abs(target - pos)
         
         # Open position
         if target > pos:
             req.offset = OFFSET_OPEN
             
             if DIRECTION_LONG in vtPositionName:
                 req.direction = DIRECTION_LONG
                 if tick.upperLimit:
                     req.price = tick.upperLimit
                 else:
                     req.price = tick.askPrice1
             elif DIRECTION_SHORT in vtPositionName:
                 req.direction = DIRECTION_SHORT
                 if tick.lowerLimit:
                     req.price = tick.lowerLimit
                 else:
                     req.price = tick.bidPrice1
             
             self.mainEngine.sendOrder(req, contract.gatewayName)
         
         # Close position
         elif target < pos:
             req.offset = OFFSET_CLOSE
             
             if DIRECTION_LONG in vtPositionName:
                 req.direction = DIRECTION_SHORT
                 if tick.upperLimit:
                     req.price = tick.upperLimit
                 else:
                     req.price = tick.askPrice1
             
             elif DIRECTION_SHORT in vtPositionName:
                 req.direction = DIRECTION_LONG
                 if tick.lowerLimit:
                     req.price = tick.lowerLimit
                 else:
                     req.price = tick.bidPrice1
                 
             # Use auto-convert for solving today/yesterday position problem
             reqList = self.mainEngine.convertOrderReq(req)
             for convertedReq in reqList:
                 self.mainEngine.sendOrder(convertedReq, contract.gatewayName)
         
         # Write log
         msg = u'发出%s委托 %s%s %s@%s' %(vtSymbol, req.direction, req.offset,
                                         req.price, req.volume)
         self.writeLog(msg)