Ejemplo n.º 1
0
    def onTick(self, tick):
        """
        :param tick:  stbase.TickData
        :return:
        """
        if self.prepared():
            return

        stbase.println(tick.code, tick.price.last, tick.price.buy_1,
                       tick.price.sell_1)
        cs = self.get_code_params(tick.code)
        print cs.name, cs.strategy_id, cs.enable, cs.value

        print '-' * 40
        print ''

        # print tick.dict()
        # print tick.json()
        # print tick.trade_object.limit_price,tick.trade_object.last_price
        # print tick.trade_object.code

        base_price = 0
        # self.strategy_inday(tick.trade_object.code, 100, 0.001)
        # to = stbase.stocks.getTradeObject(tick.trade_object.code)
        # print to.code, to.limit_price,to.last_price

        # self.strategy_inday(tick.trade_object.code, 100, 0.001)
        pass
Ejemplo n.º 2
0
    def start(self):
        from table import make_table

        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")

        cfgs = self.param_table
        params = cfgs.get("PARAMS")

        entries = []
        if not cfgs.get("TEST_ARRAY"):
            entries = make_table(params)
        else:
            entries = cfgs.get("TEST_ARRAY" )

        for idx, bar in enumerate(self.bar_list):
            bar.index = idx

        name_ov = 'runtest_overview_{}_{}.txt'.format(SYMBOL,INDEX)
        if os.path.exists(name_ov):
            os.remove(name_ov)

        # for pandas excel

        fields = OrderedDict(params=[],open_times=[], close_times=[],
                             fee=[],
                   profit=[],date_range=[],sample_num=[],
                   sample_unit=[],init_funds=[],curr_funds=[],curr_margin=[] )
        


        global STOP_WIN ,STOP_WIN_MIN ,N ,TIMEPERIOD,INIT_FUNDS ,LOT_PER_UNIT

        self.overview_report_ready()

        for p in entries:
            STOP_WIN = p['stop_win']
            STOP_WIN_MIN = p['stop_win_min']
            TIMEPERIOD = p['timeperiod']
            N = p['n']

            print '>>', STOP_WIN ,STOP_WIN_MIN ,N ,TIMEPERIOD
            # From Here
            self.reset()

            for bar in self.bar_list:
                self.onBar(bar)

            self.output_file = open(name_ov, 'a+')
            self.reportView(fields)

            # 净值处理
            self.data_net_report()

            self.overview_report_datarecord()


        self.overview_report_write()
        df = pd.DataFrame(fields)
        df.to_excel("runtest_overview_{}_{}.xlsx".format(SYMBOL,INDEX))
Ejemplo n.º 3
0
    def start(self):
        self.set_params(run=self.Runnable.STOP, start='false')  # 停止
        codes = self.get_codes()
        for code in codes:
            self.set_code_params(code.code, open_allow=True, cover_allow=True)

        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")
Ejemplo n.º 4
0
    def start(self):
        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")

        code = '0600000'
        to = stbase.stocks.getTradeObject(code)
        pos = self.product.getPosition(code)
        stbase.println(pos.dict())
        amount = self.product.getAmountUsable()
        asset = self.product.getAmountAsset()
Ejemplo n.º 5
0
 def onBar(self, bar):
     """
     :param bar: stbase.BarData
     :return:
     bar.cycle : ['1m','5m','15m','30m','60m','d','w','m','q','y']
     bar.code :
     bar.trade_object :
     .open .close .high .low .vol .amount .time
     """
     stbase.println(bar.code, bar.cycle, bar.close, bar.vol)
Ejemplo n.º 6
0
 def onTick(self, tick):
     """
     :param tick:  stbase.TickData
     :return:
     """
     # self.zf.onTick(tick)
     stbase.println(tick.code, tick.price.last, tick.price.buy_1,
                    tick.price.sell_1)
     cs = self.get_code_params(tick.code)
     print cs.name, cs.strategy_id, cs.enable, cs.value
Ejemplo n.º 7
0
    def onTick(self,tick):
        """
        :param tick:  stbase.TickData
        :return:
        """
        stock = stbase.futures.getTradeObject(tick.code)

        # 写入交易股票的当前价格
        cp = model.CodePrice.get(code=tick.code)
        if not cp :
            cp = model.CodePrice()
            cp.code = tick.code
            cs = self.get_code_params(tick.code)
            cp.name = cs.name
        cp.assign(tick.price.dict())
        cp.assign(dict(yd_close=stock.yd_close))
        cp.save()

        # 记录当前股票持仓信息
        model.CodePosition.collection().remove({'InstrumentID':tick.code})
        # cp = model.CodePosition.get(code=tick.code,strategy_id=self.id)
        # if not cp:
        #     cp = model.CodePosition()
        for pos in self.getPosition(tick.code): # []
            print pos
        # cp.assign(pos.dict())
        # cp.code = tick.code
        # cs = self.get_code_params(tick.code)
        # cp.name = cs.name
        # cp.strategy_id = self.id
        # cp.save()


        stbase.println(tick.code, tick.price.last, tick.price.buy_1, tick.price.sell_1)
        cs = self.get_code_params(tick.code)
        print cs.name, cs.strategy_id, cs.enable, cs.value
        # self.do_zf(tick)
        print '-'*40
        print ''



        # print tick.dict()
        # print tick.json()
        # print tick.trade_object.limit_price,tick.trade_object.last_price
        # print tick.trade_object.code

        base_price = 0
        # self.strategy_inday(tick.trade_object.code, 100, 0.001)
        # to = stbase.stocks.getTradeObject(tick.trade_object.code)
        # print to.code, to.limit_price,to.last_price

        # self.strategy_inday(tick.trade_object.code, 100, 0.001)
        pass
Ejemplo n.º 8
0
    def start(self):
        self.set_params(run=self.Runnable.STOP,start='false')  # 停止
        codes =  self.get_codes()
        for code in codes:
            self.setCodeParams(code.code,open_allow=True,cover_allow=True)
            print code.code
        # self.startTimer(self.limit_buy,timeout=2)

        self.subBar(SYMBOL, '1m')     # 手动订阅指定的合约k线,一遍得到k线播放事件

        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")
Ejemplo n.º 9
0
    def start(self):
        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")

        # for _ in  stbase.stocks.market.getHistoryBars(self.CODES[0],limit=5):
        #     print _.time
        # code = '0600000'
        # to = stbase.stocks.getTradeObject(code)
        # pos = self.product.getPosition(code)
        # stbase.println(pos.dict())
        # amount = self.product.getAmountUsable()
        # asset = self.product.getAmountAsset()

        # stbase.println('amount:{}'.format(amount) )
        # stbase.println('asset:{}'.format(asset)  )

        self.startTimer(timeout=1)
Ejemplo n.º 10
0
    def onTimer(self, timer):
        print 'ontimer..'
        # timer.start()
        code = '0600000'
        obj = stbase.stocks.getTradeObject(code)
        # print obj.last_price

        # print obj.price.dict()
        # print 'on buy() or sell() ..'
        # self.buy('0600000',obj.price.sell_1,100)
        # self.sell('0600000',obj.price.buy_1,100)

        # 以最低价下委托买入
        for _ in range(1):
            stbase.println('try buy({})..'.format(obj.min_price))
            self.buy(code, obj.min_price, 100)
            #
            # stbase.println('try sell({})..'.format(30))
            # self.sell(code, obj.max_price, 100)
            time.sleep(1)
Ejemplo n.º 11
0
    def onTick(self, tick):
        """
        :param tick:  stbase.TickData
        :return:
        """
        stock = stbase.stocks.getTradeObject(tick.code)

        # 写入交易股票的当前价格
        cp = model.CodePrice.get(code=tick.code)
        if not cp:
            cp = model.CodePrice()
            cp.code = tick.code
            cs = self.get_code_params(tick.code)
            cp.name = cs.name
        cp.assign(tick.price.dict())
        cp.assign(dict(yd_close=stock.yd_close))

        cp.save()

        # 记录当前股票持仓信息
        cp = model.CodePosition.get(code=tick.code, strategy_id=self.id)
        if not cp:
            cp = model.CodePosition()
        pos = self.getPosition(tick.code)
        cp.assign(pos.dict())
        cp.code = tick.code
        cs = self.get_code_params(tick.code)
        cp.name = cs.name
        cp.strategy_id = self.id
        cp.save()

        stbase.println(tick.code, tick.price.last, tick.price.buy_1,
                       tick.price.sell_1)
        cs = self.get_code_params(tick.code)
        print cs.name, cs.strategy_id, cs.enable, cs.value
        self.do_zf(tick)
        print '-' * 40
        print ''
Ejemplo n.º 12
0
    def start(self):
        """不能在start 中调用 stbase.controller.stop()"""
        stbase.Strategy.start(self)
        stbase.println("Strategy : {} Started..".format(self.id))

        with open("{}.pid".format(self.id),'w') as f:
            f.write(str(os.getpid()))
            f.flush()
        self.set_params(pid = os.getpid())

        self.code = self.get_codes()[0].code

        self.log_print(message="Strategy Start..")


        if sys.argv[-1] == 'run': # 正式运行委托下单打开
            self.order_enable = True

        if self.order_enable:
            self.startTimer(timeout=2)   # 启动定时器,定时上报策略运行状态
        else:
            self.exec_wr_atr()  # 执行策略,仅仅输出信号文件
            self.plot_view()
            stbase.controller.stop()
Ejemplo n.º 13
0
    def start(self):
        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")

        code = '0600000'
        code = '0600736'
        to = stbase.stocks.getTradeObject(code)
        pos = self.product.getPosition(code)
        # stbase.println(pos.dict())
        print pos
        amount = self.product.getAmountUsable()
        asset = self.product.getAmountAsset()
        print amount, asset
        # stbase.println('amount:{}'.format(amount) )
        # stbase.println('asset:{}'.format(asset)  )

        # self.startTimer(timeout=5)
        # return

        # 打印持仓信息
        # pos_list = self.getPosition()
        # for pos in pos_list:
        #     stbase.println( 'code:%s , yd_qty:%s'%(pos.code,pos.qty_yd))
        #
        # 打印委托记录(在委托中..)
        # orders = self.getOrders(order_id=111)
        # orders = self.getOrders()
        # for order in orders:
        #     stbase.println( order )
        #     self.cancelOrder(order.order_id)

        # self.cancelOrder(390941)

        ks = self.product.market.getHistoryBars(code, cycle='1m')
        close = map(lambda _: _.close, ks)
        print close
Ejemplo n.º 14
0
    def onTimer(self,timer):

        from mantis.sg.fisher.ctp import TickFix
        codes = self.get_codes()
        # obj = stbase.controller.futures.getTradeObject( codes[0].code )


        print self.get_amount()
        print self.get_position(stbase.Constants.Short)

        cs = self.get_code_params(self.code)
        self.cs = cs

        # cs = self.get_code_params(self.code)
        # self.cs = cs
        #
        if self.last_tick : # 必须获得行情tick
            # self.order_open(self.last_tick.price.last-2,stbase.Constants.Short)
            # stbase.controller.stop()
            # return

            # 检查商品的交易时间
            prd_name = TickFix.get_product_code(self.code).upper()
            p = TickFix.Products.get(prd_name)
            if p:
                if TickFix.is_in_trading_time(self.last_tick.price.time,p):  # and TickFix.is_in_trading_time( data['SaveTime'], p):
                    try:
                        # self.order_open(0, stbase.Constants.Long)
                        self.order_close(0, stbase.Constants.Long)
                        return
                        self.exec_wr_atr()
                    except:
                        traceback.print_exc()
                    self.plot_view()
                    stbase.println( 'Strategy Has Been Executed, Wait For Shutdown..' )
                    time.sleep(2)
                    stbase.controller.stop()
                else:
                    stbase.println( 'Not in Trading Time ,skipped..')
                    timer.start()
            else:
                stbase.println( 'System Config Error , code : {} Not In TickFix Table.'.format(self.code))
                stbase.controller.stop()
        else:
            timer.start()   # repeat
            print 'Market Is Closed.'
Ejemplo n.º 15
0
 def start(self):
     stbase.Strategy.start(self)
     stbase.println("Strategy : Sample Started..")
     self.startTimer(timeout=10)
Ejemplo n.º 16
0
    def start(self):
        self.set_params(run=self.Runnable.STOP,start='false')  # 停止
        print self.get_codes()

        stbase.Strategy.start(self)
        stbase.println("Strategy : Sample Started..")
Ejemplo n.º 17
0
 def start(self):
     # self.set_params(run=self.Runnable.STOP,start='false')  # 停止
     stbase.Strategy.start(self)
     stbase.println("Strategy : Market Recorder Started..")