Esempio n. 1
0
 def __new_strategy_detail(self, is_init=False):
     self.open_steps.clear()
     self.last_step = None
     init_cash = self.strategy.budget
     #close old strategy_detail
     if self.strategy_detail: 
         self.logger.info('__new_strategy_detail: close old strategy_detail(id=%s)', self.strategy_detail.id)
         remaining_qty = TradeOrder.calc_end_qty(self.strategy_detail.id, include_today=True)
         if remaining_qty>0:
             self.logger.warning('__new_strategy_detail: cannot close old strategy_detail cause remaining_qty=%s', remaining_qty)
             return
         self.strategy_detail.end_cash = ahelper.format_money(self.strategy_detail.init_cash+TradeOrder.calc_revenue(self.strategy_detail.id))
         self.strategy_detail.is_active = False
         self.strategy_detail.updated_at = atime.now()
         self.strategy_detail.save()
         self.is_pending_close=False
         init_cash = self.strategy_detail.end_cash
         self.strategy_detail = None
         #stop this strategy
         actual_loss = self.strategy.budget-init_cash
         if self.strategy.type==StrategyType.SINGLE or actual_loss >=self.strategy.fix_loss:
             self.logger.info('__new_strategy_detail: close strategy(actual_loss=%s, allowed_loss=%s)', actual_loss, self.strategy.fix_loss)
             self.__close_strategy()
             return
         
     if not is_init and atime.today().weekday()>0:
         self.logger.info('__new_strategy_detail: Only Monday we can recreate new strategy_detail')
         return
         
     #create new strategy detail
     _start = atime.date2str(atime.calc_date(atime.today(), -30))
     _end = atime.date2str(atime.today())
     df = ts.get_hist_data(code=self.strategy.symbol,start=_start,end=_end,ktype='W')
     top_price = ahelper.format_money(df[0:2]['high'].max())
     bottom_price = ahelper.format_money(df[0:2]['low'].min())
     _count = min(int((top_price-bottom_price)//(top_price*0.01)),self.strategy.param2)
     step_delta_price = ahelper.format_money((top_price-bottom_price)/_count)
     _tmp = sum([(bottom_price+(_count-n)*step_delta_price)*(1+(n-1)*self.strategy.param1) for n in range(1,_count+1)])
     init_qty = int(init_cash/_tmp//100*100)
     _total_qty = sum([(1+(n-1)*self.strategy.param1)*init_qty for n in range(1,_count+1)])
     start_price = ahelper.format_money(init_qty*_tmp/_total_qty)
     new_sd = StrategyDetail(strategy=self.strategy,
                             top_price = top_price,
                             bottom_price = bottom_price,
                             start_price=start_price,
                             step_delta_price=step_delta_price,
                             step_count=_count+1,
                             init_qty=init_qty,
                             step_delta_qty=int(init_qty*self.strategy.param1),
                             high_stop_ratio=0.025,
                             low_stop_ratio=0.025,
                             init_cash=init_cash
                             )
     new_sd.save()
     self.logger.info('__new_strategy_detail: created new strategy_detail(id=%s)', new_sd.id)
     self.strategy_detail = new_sd
     self.lot_available = 0 
     self.cash_available = init_cash
Esempio n. 2
0
    def __place_order(self):
        if self.open_steps:
            self.logger.info(
                '__place_order: Not place order - existing open_steps: %s',
                self.open_steps)
            return

        stock_data = self.account.get_real_stocks([self.strategy.symbol])
        _close = stock_data[self.strategy.symbol]['close']
        self.price_limit_down = ahelper.format_money(_close * 0.9)
        self.price_limit_up = ahelper.format_money(_close * 1.1)
        c_price = stock_data[self.strategy.symbol]['now']
        _no = self.strategy_detail.step_no(c_price)

        self.logger.info('__place_order: _no=%s, c_price=%s, last_step=%s',
                         _no, c_price, self.last_step)
        if _no == FixedFlag.BUY_ALL:
            self.__new_open_steps(self.strategy_detail.step_count - 1, c_price)
        elif _no == FixedFlag.SELL_ALL:
            self.__new_open_steps(0, c_price)
        elif _no in (FixedFlag.HIGH_STOP, FixedFlag.LOW_STOP):
            self.__new_open_steps(0, c_price)  #sell all
            if self.open_steps:
                self.is_pending_close = True
            else:
                self.__new_strategy_detail()
        elif self.last_step is None:
            m_price = min(c_price, self.strategy_detail.start_price)
            self.__new_open_steps(self.strategy_detail.step_no(m_price),
                                  m_price)
        elif self.last_step.step_no - _no > 1:
            #sell
            self.__new_open_steps(_no + 1, c_price)
            #buy
            self.__new_open_steps(
                self.last_step.step_no + 1,
                self.strategy_detail.step_price(self.last_step.step_no + 1))
        elif _no - self.last_step.step_no >= 1:
            #buy
            self.__new_open_steps(_no, c_price)
            #sell
            if self.last_step.step_no > 0:
                self.__new_open_steps(
                    self.last_step.step_no - 1,
                    self.strategy_detail.step_price(self.last_step.step_no -
                                                    1))
        elif _no == self.last_step.step_no:
            if _no > 0:
                self.__new_open_steps(_no - 1,
                                      self.strategy_detail.step_price(_no - 1))
            self.__new_open_steps(_no + 1,
                                  self.strategy_detail.step_price(_no + 1))
        elif self.last_step.step_no - _no == 1:
            self.__new_open_steps(_no, self.strategy_detail.step_price(_no))
            self.__new_open_steps(_no + 2,
                                  self.strategy_detail.step_price(_no + 2))
Esempio n. 3
0
 def __save_trade_order(self, code, price, qty, bs_type):
     self.logger.info('__save_trade_order: code=%s, %s qty=%s, price=%s', code, bs_type, qty, price)
     order = TradeOrder(strategy_detail=self.strategy_detail,
                        order_code=code,
                        price=price,
                        qty=qty,
                        bs_type=bs_type)
     order.calc_fee()
     order.save()
     if bs_type==BsType.BUY:
         self.cash_available = ahelper.format_money(self.cash_available - order.fee - order.qty*order.price)
     else:
         self.cash_available = ahelper.format_money(self.cash_available - order.fee + order.qty*order.price)
         self.lot_available = self.lot_available-order.qty
     self.logger.info('__save_trade_order: cash_available=%s, lot_available=%s',self.cash_available,self.lot_available)
Esempio n. 4
0
 def low_stop_price(self):
     if not hasattr(self, '_low_stop_price'):
         self._low_stop_price = ahelper.format_money(
             self.start_price * (1 - self.step_ratio *
                                 (self.total_num - 1)) *
             (1 - self.low_stop_ratio))
     return self._low_stop_price
Esempio n. 5
0
 def __place_order(self):
     if self.open_steps:
         self.logger.info('__place_order: Not place order - existing open_steps: %s', self.open_steps)
         return
     
     stock_data = self.account.get_real_stocks([self.strategy.symbol])
     _close = stock_data[self.strategy.symbol]['close']
     self.price_limit_down = ahelper.format_money(_close*0.9)
     self.price_limit_up = ahelper.format_money(_close*1.1)
     c_price = stock_data[self.strategy.symbol]['now']
     _no = self.strategy_detail.step_no(c_price)
     
     self.logger.info('__place_order: _no=%s, c_price=%s, last_step=%s', _no, c_price, self.last_step)
     if _no==FixedFlag.BUY_ALL:
         self.__new_open_steps(self.strategy_detail.step_count-1, c_price)
     elif _no==FixedFlag.SELL_ALL:
         self.__new_open_steps(0, c_price)
     elif _no in (FixedFlag.HIGH_STOP, FixedFlag.LOW_STOP):
         self.__new_open_steps(0, c_price)#sell all
         if self.open_steps:
             self.is_pending_close = True
         else:
             self.__new_strategy_detail()
     elif self.last_step is None:
         m_price = min(c_price, self.strategy_detail.start_price)
         self.__new_open_steps(self.strategy_detail.step_no(m_price), m_price)
     elif self.last_step.step_no-_no>1:
         #sell
         self.__new_open_steps(_no+1, c_price)
         #buy
         self.__new_open_steps(self.last_step.step_no+1, self.strategy_detail.step_price(self.last_step.step_no+1))
     elif _no-self.last_step.step_no>=1:
         #buy
         self.__new_open_steps(_no, c_price)
         #sell
         if self.last_step.step_no>0:
             self.__new_open_steps(self.last_step.step_no-1, self.strategy_detail.step_price(self.last_step.step_no-1))
     elif _no==self.last_step.step_no:
         if _no>0:
             self.__new_open_steps(_no-1, self.strategy_detail.step_price(_no-1))
         self.__new_open_steps(_no+1, self.strategy_detail.step_price(_no+1))
     elif self.last_step.step_no-_no==1:
         self.__new_open_steps(_no, self.strategy_detail.step_price(_no))
         self.__new_open_steps(_no+2, self.strategy_detail.step_price(_no+2))
Esempio n. 6
0
 def fetch_quotation(self):
     if Config.IS_TEST:
         _dict = dict()
         for s in self.stock_codes:
             p = ahelper.format_money(DummyQuotationServer(s).price())
             _dict[s] = {"now": p, "ask1": p + 0.01, "bid1": p - 0.01}
         return _dict
     else:
         _data = self.source.stocks(self.stock_codes)
         _dict = dict()
         for s in self.stock_codes:
             _dict[s] = {"now": _data[s]["now"]}
         return _dict
Esempio n. 7
0
 def fetch_quotation(self):
     if Config.IS_TEST:
         _dict = dict()
         for s in self.stock_codes:
             p = ahelper.format_money(DummyQuotationServer(s).price())
             _dict[s] =  {"now":p,"ask1":p+0.01, "bid1":p-0.01}
         return _dict
     else:
         _data = self.source.stocks(self.stock_codes)
         _dict = dict()
         for s in self.stock_codes:
             _dict[s] =  {"now":_data[s]["now"]}
         return _dict
Esempio n. 8
0
 def __save_trade_order(self, code, price, qty, bs_type):
     self.logger.info('__save_trade_order: code=%s, %s qty=%s, price=%s',
                      code, bs_type, qty, price)
     order = TradeOrder(strategy_detail=self.strategy_detail,
                        order_code=code,
                        price=price,
                        qty=qty,
                        bs_type=bs_type)
     order.calc_fee()
     order.save()
     if bs_type == BsType.BUY:
         self.cash_available = ahelper.format_money(self.cash_available -
                                                    order.fee -
                                                    order.qty * order.price)
     else:
         self.cash_available = ahelper.format_money(self.cash_available -
                                                    order.fee +
                                                    order.qty * order.price)
         self.lot_available = self.lot_available - order.qty
     self.logger.info(
         '__save_trade_order: cash_available=%s, lot_available=%s',
         self.cash_available, self.lot_available)
Esempio n. 9
0
 def low_stop_price(self):
     if not hasattr(self, '_low_stop_price'):
         self._low_stop_price = ahelper.format_money(
             self.bottom_price * (1 - self.low_stop_ratio))
     return self._low_stop_price
Esempio n. 10
0
 def calc_revenue(cls, sd_id):
     orders = cls.select().join(StrategyDetail).where(StrategyDetail.id==sd_id)
     return ahelper.format_money(sum([_calc_money(o) for o in orders]))
Esempio n. 11
0
 def step_margin(self):
     if not hasattr(self, '_step_margin'):
         self._step_margin = ahelper.format_money(self.start_price *
                                                  self.step_ratio)
     return self._step_margin
Esempio n. 12
0
    def __new_strategy_detail(self, is_init=False):
        self.open_steps.clear()
        self.last_step = None
        init_cash = self.strategy.budget
        #close old strategy_detail
        if self.strategy_detail:
            self.logger.info(
                '__new_strategy_detail: close old strategy_detail(id=%s)',
                self.strategy_detail.id)
            remaining_qty = TradeOrder.calc_end_qty(self.strategy_detail.id,
                                                    include_today=True)
            if remaining_qty > 0:
                self.logger.warning(
                    '__new_strategy_detail: cannot close old strategy_detail cause remaining_qty=%s',
                    remaining_qty)
                return
            self.strategy_detail.end_cash = ahelper.format_money(
                self.strategy_detail.init_cash +
                TradeOrder.calc_revenue(self.strategy_detail.id))
            self.strategy_detail.is_active = False
            self.strategy_detail.updated_at = atime.now()
            self.strategy_detail.save()
            self.is_pending_close = False
            init_cash = self.strategy_detail.end_cash
            self.strategy_detail = None
            #stop this strategy
            actual_loss = self.strategy.budget - init_cash
            if self.strategy.type == StrategyType.SINGLE or actual_loss >= self.strategy.fix_loss:
                self.logger.info(
                    '__new_strategy_detail: close strategy(actual_loss=%s, allowed_loss=%s)',
                    actual_loss, self.strategy.fix_loss)
                self.__close_strategy()
                return

        if not is_init and atime.today().weekday() > 0:
            self.logger.info(
                '__new_strategy_detail: Only Monday we can recreate new strategy_detail'
            )
            return

        #create new strategy detail
        _start = atime.date2str(atime.calc_date(atime.today(), -30))
        _end = atime.date2str(atime.today())
        df = ts.get_hist_data(code=self.strategy.symbol,
                              start=_start,
                              end=_end,
                              ktype='W')
        top_price = ahelper.format_money(df[0:2]['high'].max())
        bottom_price = ahelper.format_money(df[0:2]['low'].min())
        _count = min(int((top_price - bottom_price) // (top_price * 0.01)),
                     self.strategy.param2)
        step_delta_price = ahelper.format_money(
            (top_price - bottom_price) / _count)
        _tmp = sum([(bottom_price + (_count - n) * step_delta_price) *
                    (1 + (n - 1) * self.strategy.param1)
                    for n in range(1, _count + 1)])
        init_qty = int(init_cash / _tmp // 100 * 100)
        _total_qty = sum([(1 + (n - 1) * self.strategy.param1) * init_qty
                          for n in range(1, _count + 1)])
        start_price = ahelper.format_money(init_qty * _tmp / _total_qty)
        new_sd = StrategyDetail(strategy=self.strategy,
                                top_price=top_price,
                                bottom_price=bottom_price,
                                start_price=start_price,
                                step_delta_price=step_delta_price,
                                step_count=_count + 1,
                                init_qty=init_qty,
                                step_delta_qty=int(init_qty *
                                                   self.strategy.param1),
                                high_stop_ratio=0.025,
                                low_stop_ratio=0.025,
                                init_cash=init_cash)
        new_sd.save()
        self.logger.info(
            '__new_strategy_detail: created new strategy_detail(id=%s)',
            new_sd.id)
        self.strategy_detail = new_sd
        self.lot_available = 0
        self.cash_available = init_cash
Esempio n. 13
0
 def high_stop_price(self):
     if not hasattr(self, '_high_stop_price'):
         self._high_stop_price = ahelper.format_money(
             (self.start_price + self.step_margin) *
             (1 + self.high_stop_ratio))
     return self._high_stop_price
Esempio n. 14
0
 def high_stop_price(self):
     if not hasattr(self, '_high_stop_price'):
         self._high_stop_price = ahelper.format_money((self.start_price+self.step_margin)*(1+self.high_stop_ratio))
     return self._high_stop_price
Esempio n. 15
0
 def low_stop_price(self):
     if not hasattr(self, '_low_stop_price'):
         self._low_stop_price = ahelper.format_money(self.start_price*(1-self.step_ratio*(self.total_num-1))*(1-self.low_stop_ratio))
     return self._low_stop_price
Esempio n. 16
0
 def step_price(self, _no):
     return ahelper.format_money(self.top_price -
                                 _no * self.step_delta_price)
Esempio n. 17
0
 def step_margin(self):
     if not hasattr(self, '_step_margin'):
         self._step_margin = ahelper.format_money(self.start_price*self.step_ratio)
     return self._step_margin
Esempio n. 18
0
 def calc_fee(self):
     if self.bs_type==BsType.BUY:
         self.fee = ahelper.format_money(self.qty*self.price*0.0003)
     else:
         _amount = self.qty*self.price
         self.fee = ahelper.format_money(_amount*0.0003+max(_amount*0.001,5))
Esempio n. 19
0
 def high_stop_price(self):
     if not hasattr(self, '_high_stop_price'):
         self._high_stop_price = ahelper.format_money(
             self.top_price * (1 + self.high_stop_ratio))
     return self._high_stop_price
Esempio n. 20
0
 def step_price(self, _no):
     return ahelper.format_money(self.top_price-_no*self.step_delta_price)
Esempio n. 21
0
 def low_stop_price(self):
     if not hasattr(self, '_low_stop_price'):
         self._low_stop_price = ahelper.format_money(self.bottom_price*(1-self.low_stop_ratio))
     return self._low_stop_price
Esempio n. 22
0
 def high_stop_price(self):
     if not hasattr(self, '_high_stop_price'):
         self._high_stop_price = ahelper.format_money(self.top_price*(1+self.high_stop_ratio))
     return self._high_stop_price