コード例 #1
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def __lhb_identity_buy(self, lhb_pair, date, symbol):
        """Performs operation __lhb_identity_buy blah.
            龙虎榜买方方身份信息判断
        Attributes:
            lhb_pair:龙虎榜买卖方信息
            date:交易日期
            symbol:交易标的

        买方席位中有重要身份,只要买方总量大于卖方总量则可以下单
        """

        is_identity = 0
        latest_bize = None
        for k, bize_lhb in lhb_pair.code_bize_buy().items():
            if bize_lhb.bize().identity() == 100 or bize_lhb.bize().identity(
            ) == 1 or bize_lhb.bize().identity() == 2 or bize_lhb.bize(
            ).identity() == 3:
                is_identity = 1
                latest_bize = bize_lhb.bize()
                break
        if is_identity == 0:
            return False

        # 含有重要席位,买方总额大于卖方总额
        if lhb_pair.buy_amount() <= lhb_pair.sale_amount():
            MLog.write().info(
                '%d %s 卖方没有特殊席位,买方中有%s, 但买总额(%d)小于等于卖方总额(%d)不能下单' %
                (date, symbol, latest_bize.identity_name(),
                 lhb_pair.buy_amount(), lhb_pair.sale_amount()))
            return False

        MLog.write().info('%d %s 卖方没有特殊席位,买方中有%s, 买总额(%d)大于卖方总额(%d),可以下单' %
                          (date, symbol, latest_bize.identity_name(),
                           lhb_pair.buy_amount(), lhb_pair.sale_amount()))
        return True
コード例 #2
0
 def on_volume(self, vol, order):
     # 从委托队列中删除
     # pdb.set_trace()
     del self.__limit_order[vol.order_id()]
     self.__history_limit_volumes[vol.trader_id()] = vol
     self.__history_limit_order[order.order_id()] = order
     vol.dump()
     # 判断是开仓还是平仓
     if vol.comb_offset_flag() == CombOffset.open: # 开仓
         if vol.direction() == Direction.buy_direction: # 多头仓
             # self.long_volumes[vol.symbol()] = vol
             self.long_volumes[vol.trader_id()] = vol
         else: # 空头仓
            # self.short_volumes[vol.symbol()] = vol
             self.short_volumes[vol.trader_id()] = vol
         self.__account.open_cash(order.margin(),vol.margin(), order.fee(), vol.fee())
     else: # 平仓
         # pdb.set_trace()
         MLog.write().debug("close position account:")
         if vol.direction() == Direction.buy_direction: # 平空头仓
             if self.short_volumes.has_key(order.hold_volume_id()):
                 v = self.short_volumes[order.hold_volume_id()]
                 # self.__account.set_close_profit(v,vol)
                 del self.short_volumes[order.hold_volume_id()]
         else: # 平多头仓
             if self.long_volumes.has_key(order.hold_volume_id()):
                 v = self.long_volumes[order.hold_volume_id()]
                 # self.__account.set_close_profit(v,vol)
                 del self.long_volumes[order.hold_volume_id()]
         self.__account.close_cash(v,vol,order.fee())
     self.__account.dump()
コード例 #3
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def __lhb_identity_strategy(self, lhb_pair):
        """Performs operation __lhb_identity_strategy blah.
            判断龙虎榜买卖方身份
        Attributes:
            lhb_pair:龙虎榜买卖方信息
        """

        symbol = lhb_pair.symbol()
        date = lhb_pair.date()
        lhb_chg = self.lhb[lhb_pair.chg_type()]
        if lhb_chg.direction() == -1:  # 负面上榜不下单
            MLog.write().info(
                '%d: %d %s %s 负面上榜不下单' %
                (date, lhb_chg.direction(), symbol, lhb_chg.name()))
            return False

        # 检测卖方中是否含有机构,知名游资,一线游资,敢死队
        if self.__lhb_identity_sale(lhb_pair.code_bize_sale(), date,
                                    symbol) == False:
            return -1

        buy_singal = self.__lhb_identity_buy(lhb_pair, date, symbol)

        if buy_singal:
            return 1

        MLog.write().info('%d %s 买卖双方没有特殊席位' % (date, symbol))
        return 0
コード例 #4
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def __position_trade(self, date, daily_price, position):
        """Performs operation __position_trade blah.
            持仓判断,是否达到止盈止损
        Attributes:
            date:交易日
            daily_price:当天日行情
            position:标的的持仓信息
        """

        if date <= position.create_time():  # 防止當天購買又當天賣出情況
            return

        sl_price = position.limit_price() * (1 - self.__sl)  # 止损价
        tp_price = position.limit_price() * (1 + self.__tp)  # 止盈价

        high_price = daily_price.today_high()
        low_price = daily_price.today_low()

        # 判断是否达到止盈
        if tp_price <= high_price:
            MLog.write().debug('日期:%d 股票:%s 达到止盈价,可以平仓 止盈价:%f, 最高价:%f' %
                               (date, position.symbol(), tp_price, high_price))
            self.order_close(position.symbol(), tp_price, position.trader_id(),
                             1, date)
        if sl_price >= low_price:
            MLog.write().debug('日期:%d 股票:%s 达到止损价,可以平仓 止损价:%f, 最低价:%f' %
                               (date, position.symbol(), sl_price, low_price))
            self.order_close(position.symbol(), sl_price, position.trader_id(),
                             1, date)
コード例 #5
0
 def __short_operation(self, next_price, last_bar, amount):
     self.cancel_order()
     # 是否持有空头仓
     if len(self.short_volumes) == 0:
         if self.__is_short_order(last_bar.last_buy_price(), last_bar.close_price(), next_price) == 1:
             order = self.__short_open(last_bar.last_buy_price(), amount, last_bar.current_time())
             order.dump()
             self.__account.insert_order_cash(order.margin(), order.fee())
             self.__working_limit_order[order.order_id()] = order
             self.__limit_order[order.order_id()] = order
             self.__account.dump()
     else:
         for k,v in self.short_volumes.items():
             MLog.write().debug("hold short volumens:%d price:%f close_price:%f" %(v.amount(),v.limit_price(),last_bar.close_price()))
     # 是否持有多头仓
     if len(self.long_volumes) > 0: 
         MLog.write().debug("short singal start close long volume")
         for k,v in self.long_volumes.items():
             order = self.__long_close(last_bar.last_buy_price(), v.amount(), last_bar.current_time())
             order.set_hold_volume_id(v.trader_id())
             self.__account.insert_order_cash(order.margin(), order.fee())
             self.__working_limit_order[order.order_id()] = order
             self.__limit_order[order.order_id()] = order
             order.dump()
             self.__account.dump()
コード例 #6
0
ファイル: bar.py プロジェクト: flaght/backtesting
 def dump(self):
     MLog.write().debug(
         "current_time:%d open_price:%f close_price:%f high_price:%f low_price:%f volume:%d, last_sell_price:%f, last_buy_price:%f, last_sell_vol:%d, last_buy_vol:%d"
         % (self.__current_time, self.__open_price, self.__close_price,
            self.__high_price, self.__low_price, self.__volume,
            self.__last_sell_price, self.__last_buy_price,
            self.__last_sell_vol, self.__last_buy_vol))
コード例 #7
0
ファイル: bize_lhb.py プロジェクト: flaght/nirvana
 def dump(self):
     MLog.write().debug(
         'symbol:%s,trade_date:%d,chg_type:%s,bize_code:%s,bize_name:%s,amount:%f,buy_vol:%f,buy_amount:%f,sale_vol:%f,sale_amount:%f,desc:%s'
         % (self.__symbol, self.__trade_date, self.__chg_type,
            self.__bize_code, self.__bize_name, self.__amount,
            self.__buy_vol, self.__buy_amount, self.__sale_vol,
            self.__sale_amount, self.__desc))
コード例 #8
0
ファイル: sqlite_ext.py プロジェクト: flaght/nirvana
 def create_table(self, sql):
     if sql is not None and sql != '':
         cur = self.__get_cursor()
         cur.execute(sql)
         self.conn.commit()
         self.__close_all(cur)
     else:
         MLog.write().error('the [{}] is empty or equal None!'.format(sql))
コード例 #9
0
 def __is_short_order(self, order_price, close_price, next_price):
     short_fee = (order_price * self.__instrument.min_limit_order_volume() * self.__instrument.fee()) * 2
     short_profit = abs(order_price - next_price) * self.__instrument.min_limit_order_volume() # 空头最小利润
     
     if short_profit > short_fee:
         MLog.write().debug('short_profit:%f more than short_fee:%f allow  open short'%(short_profit, short_fee))
     else:
         MLog.write().debug('short_profit:%f less than short_fee:%f not open short'%(short_profit, short_fee))
     return 1 if short_profit > short_fee else 0
コード例 #10
0
 def __is_long_order(self, order_price, close_price, next_price):
     long_fee = (order_price * self.__instrument.min_limit_order_volume() * self.__instrument.fee()) * 2  # 多头建仓手续费
     long_profit = abs(order_price - next_price) * self.__instrument.min_limit_order_volume() # 多头最小利润
     
     if long_profit > long_fee:
         MLog.write().debug('long_profit:%f more than long_fee:%f allow open long'%(long_profit, long_fee))
     else:
         MLog.write().debug('long_profit:%f less than long_fee:%f not open long'%(long_profit, long_fee))
     return 1 if long_profit > long_fee else 0
コード例 #11
0
 def dump(self):
     MLog.write().debug(
         'trade_date:%d,symbol:%s,latest_price:%f,today_open:%f,today_close:%f,today_high:%f,today_low:%f,vol:%f,amount:%f,change:%f,pchg:%f,amplitude:%f,deals:%f,avg_price:%f,avg_vol:%f,avgtramt:%f,turnrate:%f,totmktcap:%f,negotiablemv:%f'
         % (self.__trade_date, self.__symbol, self.__latest_price,
            self.__today_open, self.__today_close, self.__today_high,
            self.__today_low, self.__vol, self.__amount, self.__change,
            self.__pchg, self.__amplitude, self.__deals, self.__avg_price,
            self.__avg_vol, self.__avgtramt, self.__turnrate,
            self.__totmktcap, self.__negotiablemv))
コード例 #12
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def calc_settle(self, date, daily_price_list):
        """Performs operation calc_settle blah.
            收盘后对当日进行结算
        Attributes:
            daily_price_list:当日行情列表
            date:交易日
        """
        daily_profit = 0.0
        daily_cost = 0.0
        MLog.write().debug('calc_settle trade_date:%d' % date)
        for vid, value in self.long_volumes.items():
            if not daily_price_list.has_key(value.symbol()[2:]):
                continue
            daily_price = daily_price_list[value.symbol()[2:]]

            # 若停牌则以最近收盘价为结算价
            if daily_price.is_use() == 0:
                settle_price = daily_price.latest_price()

            else:
                settle_price = daily_price.today_close()

            value.set_settle_price(date, settle_price)

            daily_profit += value.daily_profit()

            daily_cost += value.cost()
            # MLog.write().debug('symbol:%s, settle_price %f, limit_pricee:%f, daily_profit:%f profit:%f' % (
            #    value.symbol(), settle_price, value.limit_price(), value.daily_profit(), value.profit()))

            self.long_volumes[vid] = value

            if self.history_limit_volumes.has_key(vid):
                self.history_limit_volumes[vid] = value

        # MLog.write().debug('date:%d, position daily_profit:%f' % (date, daily_profit))

        daily_fee = 0.0
        for vid, vvol in self.history_limit_volumes.items():
            daily_fee += vvol.fee()

        self.account.set_position_profit(daily_profit)
        record = DailyRecord()
        record.set_position_cost(daily_cost)  # 当日持仓成本
        record.set_close_profit(self.account.close_profit())  # 当日平仓盈亏
        record.set_position_profit(self.account.position_profit())  # 当日持仓盈亏
        record.set_limit_volume(self.history_limit_volumes)  # 当日交易记录
        record.set_limit_order(self.__history_limit_order)  # 当日下单记录
        record.set_long_volume(self.long_volumes)  # 当日持仓记录
        record.set_fee(daily_fee)  # 当日手续费消耗
        record.set_mktime(date)

        self.__trader_record[record.mktime()] = record
        self.account.reset()
        self.__reset()
コード例 #13
0
ファイル: sqlite_ext.py プロジェクト: flaght/nirvana
 def save(self, sql, data):
     '''插入数据'''
     if sql is not None and sql != '':
         if data is not None:
             cur = self.__get_cursor()
             for d in data:
                 cur.execute(sql, d)
                 self.conn.commit()
             self.__close_all(cur)
     else:
         MLog.write().error('the [{}] is empty or equal None!'.format(sql))
コード例 #14
0
ファイル: xq_lhb_client.py プロジェクト: flaght/nirvana
 def run_crawler_lhb_detail(self, symbol, end_date):
     url = self.__base_detail + '?symbol=' + symbol + '&date=' + str(
         end_date)
     MLog.write().info('%s' % (url))
     lhb_detail_obj = json.loads(self.__client.request(url))
     if lhb_detail_obj is None:
         return None
     lhb_detail = lhb_detail_obj.get('detail')
     if lhb_detail is None:
         return None
     return lhb_detail
コード例 #15
0
ファイル: sqlite_ext.py プロジェクト: flaght/nirvana
 def drop_table(self, table):
     """如果表存在,则删除表,如果表中存在数据的时候,使用该
     方法的时候要慎用!"""
     if table is not None and table != '':
         sql = 'DROP TABLE IF EXISTS ' + table
         cur = self.__get_cursor()
         cur.execute(sql)
         self.conn.commit()
         self.__close_all(cur)
     else:
         MLog.write().error(
             'the [{}] is empty or equal None!'.format(table))
コード例 #16
0
ファイル: sqlite_ext.py プロジェクト: flaght/nirvana
    def __conection_sql(self):
        try:
            self.conn = sqlite3.connect(self.name, self.timeout)
            if os.path.exists(self.name) and os.path.isfile(self.name):
                self.type = 0
            else:
                self.conn = sqlite3.connect(':memory:')
                self.type = 1

        except Exception, e:
            MLog.write().error('sqlite3 error:%s' % e)
            return
コード例 #17
0
ファイル: sqlite_ext.py プロジェクト: flaght/nirvana
 def __get_conn(self, path):
     """获取到数据库的连接对象,参数为数据库文件的绝对路径
     如果传递的参数是存在,并且是文件,那么就返回硬盘上面改
     路径下的数据库文件的连接对象;否则,返回内存中的数据接
     连接对象"""
     conn = sqlite3.connect(path)
     if os.path.exists(path) and os.path.isfile(path):
         MLog.write().error('硬盘上面:[{}]'.format(path))
         return conn
     else:
         conn = None
         MLog.write().error('内存上面:[:memory:]')
         return sqlite3.connect(':memory:')
コード例 #18
0
ファイル: xq_lhb_client.py プロジェクト: flaght/nirvana
 def run_crawler_lhb(self, end_date):
     lhb_dict = {}
     url = self.__base_list + '?date=' + str(end_date)
     MLog.write().info('%s' % (url))
     lhb_obj = json.loads(self.__client.request(url))
     lhb_list = lhb_obj.get('list')
     if lhb_list is None:
         return
     for lhb in lhb_list:
         symbol = lhb.get('symbol')
         detail = self.run_crawler_lhb_detail(symbol, end_date)
         if detail:
             lhb_dict[symbol] = detail
     return lhb_dict
コード例 #19
0
    def dump(self):
        str = '异常单'
        if self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.buy_direction:
            str = '多头开仓'
        elif self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.sell_direction:
            str = '空头开仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.buy_direction:
            str = '空头平仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.sell_direction:
            str = '多头平仓'

        MLog.write().info('[%s]--->%s Volume:订单ID:%d, 委托单ID:%d, 方向:%d, 成交价:%f, 成本(不含手续费):%f, 佣金:%f, 转让费:%f, 印花税:%f, 手续费:%f, 当日盈亏:%f, 累计盈亏:%f,今日结算价:%f 订单类型:%d, 手数:%d, 成交时间:%d, strategy_id:%d, 最小成交单位量:%d'%(
            str, self.__symbol, self.__trader_id, self.__order_id, self.__direction.value, self.__limit_price, self.cost(), self.__commission, self.__transfer, self.__stamp,
            self.fee(), self.__daily_profit, self.__profit, self.__daily_settle_price, self.__comb_offset_flag.value,self.__amount,self.__create_time,
            self.__strategy_id,self.__min_volume))
コード例 #20
0
ファイル: account.py プロジェクト: flaght/nirvana
 def insert_order_cash(self, cost, fee):
     """Performs operation insert_order_cash blah.
         挂单资金操作, 本身消耗,手续费, 平仓挂单只有手续费消耗
     Attributes:
         cost: 开仓成本(不包含手续费)
         fee: 相关手续费
     """
     if self.__available_cash < cost:  # 可用资金不够时,补充资金
         MLog.write().debug('新增资金 100000')
         self.set_init_cash(100000)
     self.__available_cash -= (cost + fee)  # 消耗的可用资金数
     self.__cost += (cost)
     self.__locked_cash += (cost + fee)  # 挂单时被锁定的资金
     self.__fee += fee  # 消耗的手续费
     self.__withdraw += (cost + fee)  # 出去的资金
コード例 #21
0
    def record(self):
        self.__account.dump()
        record = DailyRecord()
        record.set_close_profit(self.__account.close_profit())
        record.set_position_profit(self.__account.position_profit())
        record.set_commssion(self.__account.commission())
        record.set_limit_volume(self.__history_limit_volumes)
        record.set_limit_order(self.__history_limit_order)
        
        
        record.set_mktime(self.__bar_list[-1].mktime())

        MLog.write().info('mkdate:%d, available_cash:%f,profit:%f'%(record.mktime(),self.__account.available_cash(), record.all_profit()))
        self.__trader_record[record.mktime()] = record
        self.__account.reset()
        self.__reset()
コード例 #22
0
    def calc_result(self):
        max_profit = 0.0
        total_profit = 0.0
        base_value = 0.0
        for key,value in self.__trader_record.items():
            total_profit += value.all_profit()

        starting_cash = self.__account.starting_cash()
        base_value = (int(abs(total_profit) / starting_cash) + 1) * self.__account.starting_cash()
        MLog.write().info('all:%f, base_value:%f',total_profit,base_value)
        total_profit = 0.0

        df = pd.DataFrame(columns = ['mktime','interests','value','retrace','chg','log_chg','profit'])
        # 计算每日权益,每日净值, 涨跌幅,回撤,日对数收益
        last_value = 0.0
        for mktime,daily_record in self.__trader_record.items():
            daily_record.set_base_value(base_value)
            daily_record.set_last_value(last_value)
            daily_record.set_max_profit(max_profit)
            daily_record.set_last_profit(total_profit)
            daily_record.calc_result()
            daily_record.dump()
            df = df.append(pd.DataFrame({'mktime':mktime, 'interests':daily_record.interests(),
                                         'value':daily_record.value(), 'retrace': daily_record.retrace(),
                                         'chg':daily_record.chg(),'log_chg':daily_record.log_chg(),
                                         'profit':daily_record.all_profit()},index=['mktime']), ignore_index=True)

            total_profit += daily_record.all_profit()
            if max_profit < total_profit:
                max_profit = total_profit
            last_value = daily_record.value()
            base_value += daily_record.all_profit()
            
        chg_mean = np.mean(df['log_chg'])
        chg_std = np.std(df['log_chg'])

        summary_record = SummaryRecord()
        summary_record.set_chg_mean(chg_mean)
        summary_record.set_chg_std(chg_std)
        summary_record.set_trade_count(df.shape[0])
        summary_record.set_final_value(df['value'].values[-1])
        summary_record.set_max_retr(np.min(df['retrace']))


        summary_record.calc_record(df[df['chg'] > 0.00].shape[0])
        summary_record.dump()
        df.to_csv('result_strange.csv', encoding = 'utf-8')
コード例 #23
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def calc_result(self):
        """Performs operation calc_result blah.
            计算当日的权益,净值,涨跌幅,回撤等
        Attributes:
        """

        max_profit = 0.0
        total_profit = 0.0
        for key, value in self.__trader_record.items():
            total_profit += value.all_profit()

        starting_cash = self.account.starting_cash()
        base_value = (int(abs(total_profit) / starting_cash) +
                      1) * self.account.starting_cash()
        MLog.write().debug('all:%f, base_value:%f' %
                           (total_profit, base_value))
        total_profit = 0.0

        summary_record = SummaryRecord()
        # 计算每日权益,每日净值, 涨跌幅,回撤,日对数收益
        last_value = 1.0
        last_available_cash = base_value
        for mktime, daily_record in self.__trader_record.items():
            daily_record.set_base_value(base_value)
            daily_record.set_last_value(last_value)
            daily_record.set_max_profit(max_profit)
            daily_record.set_last_profit(total_profit)
            daily_record.set_last_available_cash(last_available_cash)
            daily_record.calc_result()
            daily_record.dump()
            summary_record.record_volume(daily_record.mktime(),
                                         daily_record.volume_tocsv(),
                                         daily_record.position_tocsv())
            summary_record.record_order(daily_record.mktime(),
                                        daily_record.order_tocsv())

            summary_record.record_daily(daily_record.to_csv(),
                                        daily_record.to_dataframe())

            total_profit += daily_record.all_profit()
            if max_profit < total_profit:
                max_profit = total_profit
            last_value = daily_record.value()
            last_available_cash = daily_record.last_available_cash()

        summary_record.calc_record()
        summary_record.summary_record()
コード例 #24
0
ファイル: volume.py プロジェクト: flaght/backtesting
    def dump(self):
        str = '异常单'
        if self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.buy_direction:
            str = '多头开仓'
        elif self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.sell_direction:
            str = '空头开仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.buy_direction:
            str = '空头平仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.sell_direction:
            str = '多头平仓'

        MLog.write().debug(
            '[%s]--->Volume:trader_id:%d, order_id:%d, direction:%d, limit_price:%f, margin:%f, fee:%f, comb_offset_flag:%d, amount:%d, create_time:%d, strategy_id:%d, min_volume:%d'
            % (str, self.__trader_id, self.__order_id, self.__direction.value,
               self.__limit_price, self.__margin, self.__fee,
               self.__comb_offset_flag.value, self.__amount,
               self.__create_time, self.__strategy_id, self.__min_volume))
コード例 #25
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
 def __lhb_identity_sale(self, bize_sale, date, symbol):
     """Performs operation __lhb_identity_sale blah.
         龙虎榜卖方身份信息判断
     Attributes:
         bize_sale:龙虎榜卖方信息
         date:交易日期
         symbol:交易标的
     """
     for k, bize_lhb in bize_sale.items():
         if bize_lhb.bize().identity() == 100 or bize_lhb.bize().identity(
         ) == 1 or bize_lhb.bize().identity() == 1 or bize_lhb.bize(
         ).identity() == 3:
             MLog.write().info(
                 '%d %s 卖方席位中有%s, 不能下单' %
                 (date, symbol, bize_lhb.bize().identity_name()))
             return False
     return True
コード例 #26
0
ファイル: order.py プロジェクト: flaght/nirvana
    def dump(self):
        str = '异常单'
        if self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.buy_direction:
            str = '多头开仓'
        elif self.__comb_offset_flag == CombOffset.open and self.__direction == Direction.sell_direction:
            str = '空头开仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.buy_direction:
            str = '空头平仓'
        elif self.__comb_offset_flag == CombOffset.close and self.__direction == Direction.sell_direction:
            str = '多头平仓'

        MLog.write().debug(
            '[%s]--->Order:symbol:%s,order_id:%d,hold_vol_id:%d,amount:%d,status:%d,comb_offset_flag:%d,direction:%d,limit_price:%f,amount:%d,cost:%f,fee:%f,commission:%f,stamp:%f,transfer:%f,strategy_id:%d,create_time:%d,min_volume:%d,margin:%f'
            %
            (str, self.__symbol, self.__order_id, self.__hold_volume_id,
             self.__amount, self.__status.value, self.__comb_offset_flag.value,
             self.__direction.value, self.__limit_price, self.__amount,
             self.cost(), self.fee(), self.__commission, self.__stamp,
             self.__transfer, self.__strategy_id, self.__create_time,
             self.__min_volume, self.__margin))
コード例 #27
0
ファイル: xq_lhb_client.py プロジェクト: flaght/nirvana
    def __crawler_lhb_detail(self, symbol, trade_date):
        url = self.__base_detail + '?symbol=' + symbol + '&date=' + str(
            trade_date)
        # print (url)
        MLog.write().info('%s' % (url))
        lhb_detail_obj = json.loads(self.__client.request(url))
        if lhb_detail_obj is None:
            return
        lhb_detail = lhb_detail_obj.get('detail')
        if lhb_detail is None:
            return

        sub_path = '../../data/nirvana/output/' + str(trade_date) + '/'
        filename = sub_path + symbol + '.json'

        if not os.path.exists(sub_path):
            os.makedirs(sub_path)

        file_object = open(filename, 'w')
        file_object.write(json.dumps(lhb_detail))
        file_object.close()
コード例 #28
0
ファイル: nirvana.py プロジェクト: flaght/nirvana
    def on_volume(self, vol, order):
        """Performs operation on_volume blah.
            接收成交量单
        Attributes:
            vol:成交量单
            order:成交量单对应的委托单
        """
        # 从委托中删除
        del self.__limit_order[vol.order_id()]
        self.history_limit_volumes[vol.trader_id()] = vol
        self.__history_limit_order[order.order_id()] = order

        if vol.comb_offset_flag() == CombOffset.open:  # 开仓
            self.account.open_cash(order.cost(), vol.cost(), order.fee(),
                                   vol.fee())
            self.long_volumes[vol.trader_id()] = vol
        else:
            if self.long_volumes.has_key(order.hold_volume_id()):
                v = self.long_volumes[order.hold_volume_id()]
                profit = self.account.close_cash(v, vol, order.fee())
                MLog.write().debug('%s 平仓盈利:%f' % (vol.symbol(), profit))
                del self.long_volumes[order.hold_volume_id()]
コード例 #29
0
    def is_use(self):
        """Performs operation is_use blah.
            判断当天行情是否可用
        Attributes:
        Return:
             1 可以使用  0 不能卖,不能买 -1 不能买,可以卖  -2 不能卖,可以买
        """

        # 是否停牌
        if self.is_zero(self.__today_open) or self.is_zero(
                self.__today_close) or self.is_zero(
                    self.__today_high) or self.is_zero(self.__today_low):
            MLog.write().debug(
                '股票:%s 停盘 open:%f,close:%f,high:%f,low:%f' %
                (self.__symbol, self.__today_open, self.__today_close,
                 self.__today_high, self.__today_low))
            return 0

        sl_price = self.__latest_price * (1 - 0.1)  # 跌停
        tp_price = self.__latest_price * (1 + 0.1)  # 涨停

        # 一字跌停
        if sl_price >= self.__today_low and sl_price >= self.__today_high and (
                sl_price >= self.__today_close
                and sl_price >= self.__today_open):  # 开盘跌停一直跌停到收盘
            MLog.write().debug(
                '股票%s  一字跌停: latest_price:%f, sl_price:%f, today_low:%f, today_high:%f, today_open:%f,today_close:%f'
                % (self.__symbol, self.__latest_price, sl_price,
                   self.__today_low, self.__today_high, self.__today_open,
                   self.__today_close))
            return -2

        # 一字涨停
        if tp_price <= self.__today_low and tp_price <= self.__today_high and (
                tp_price <= self.__today_close
                and tp_price <= self.__today_open):  # 开盘涨停一直涨停到收盘
            MLog.write().debug(
                '股票%s 一字涨停: latest_price:%f, sl_price:%f, today_low:%f, today_high:%f, today_open:%f,today_close:%f'
                % (self.__symbol, self.__latest_price, sl_price,
                   self.__today_low, self.__today_high, self.__today_open,
                   self.__today_close))
            return -1

        return 1
コード例 #30
0
    def on_bar(self, bar):
        self.__bar_list.append(bar)       

        # 休盘的最后两分钟平仓
        if len(self.__bar_list) < 5:
            return
        if len(self.__bar_list) > 5:
            self.__bar_list.pop(0)
        
        next_price = self.__on_fc_single()
        close_price = self.__bar_list[-1].close_price()

        # 距行情结束还有5分钟则全部平仓
        if bar.current_time() > time.mktime(datetime.datetime(bar.mktime() / 10000,bar.mktime() / 100 % 100, bar.mktime() % 100,14,55,00).timetuple()):
            MLog.write().debug("time out start close position")
            if len(self.short_volumes) > 0:
                for k,v in self.short_volumes.items():
                    order = self.__short_close(bar.last_sell_price(), v.amount(),bar.current_time())
                    order.set_hold_volume_id(v.trader_id())
                    self.__account.insert_order_cash(order.margin(), order.fee())
                    self.__working_limit_order[order.order_id()] = order
                    self.__limit_order[order.order_id()] = order
                    order.dump()
            if len(self.long_volumes) > 0: 
                for k,v in self.long_volumes.items():
                    order = self.__long_close(bar.last_buy_price(), v.amount(), bar.current_time())
                    order.set_hold_volume_id(v.trader_id())
                    self.__account.insert_order_cash(order.margin(), order.fee())
                    self.__working_limit_order[order.order_id()] = order
                    self.__limit_order[order.order_id()] = order
                    order.dump()
            return 

        # pdb.set_trace()
        # 多仓,空仓判断
        if close_price < next_price: # 多仓信号
            MLog.write().debug("long singal start")
            self.__long_operation(next_price, self.__bar_list[-1], DEFAULT_AMOUNT)
        elif close_price > next_price: # 空仓信号
            MLog.write().debug("short singal start")
            self.__short_operation(next_price, self.__bar_list[-1], DEFAULT_AMOUNT)