예제 #1
0
파일: account.py 프로젝트: ownermz/zvt
    def on_trading_signal(self, trading_signal: TradingSignal):
        entity_id = trading_signal.entity_id
        happen_timestamp = trading_signal.happen_timestamp
        order_type = AccountService.trading_signal_to_order_type(trading_signal.trading_signal_type)
        trading_level = trading_signal.trading_level.value
        if order_type:
            try:
                kdata = get_kdata(provider=self.provider, entity_id=entity_id, level=trading_level,
                                  start_timestamp=happen_timestamp, end_timestamp=happen_timestamp,
                                  limit=1, adjust_type=self.adjust_type)
            except Exception as e:
                self.logger.error(e)
                raise WrongKdataError("could not get kdata")

            if pd_is_not_null(kdata):
                entity_type, _, _ = decode_entity_id(kdata['entity_id'][0])

                the_price = kdata['close'][0]

                if the_price:
                    self.order(entity_id=entity_id, current_price=the_price,
                               current_timestamp=happen_timestamp, order_pct=trading_signal.position_pct,
                               order_money=trading_signal.order_money,
                               order_type=order_type)
                else:
                    self.logger.warning(
                        'ignore trading signal,wrong kdata,entity_id:{},timestamp:{},kdata:{}'.format(entity_id,
                                                                                                      happen_timestamp,
                                                                                                      kdata.to_dict(
                                                                                                          orient='records')))

            else:
                self.logger.warning(
                    'ignore trading signal,could not get kdata,entity_id:{},timestamp:{}'.format(entity_id,
                                                                                                 happen_timestamp))
예제 #2
0
def get_trading_signals_figure(order_reader: OrderReader,
                               entity_id: str,
                               start_timestamp=None,
                               end_timestamp=None):
    entity_type, _, _ = decode_entity_id(entity_id)

    data_schema = get_kdata_schema(entity_type=entity_type,
                                   level=order_reader.level)
    if not start_timestamp:
        start_timestamp = order_reader.start_timestamp
    if not end_timestamp:
        end_timestamp = order_reader.end_timestamp
    kdata_reader = DataReader(entity_ids=[entity_id],
                              data_schema=data_schema,
                              entity_schema=entity_schema_map.get(entity_type),
                              start_timestamp=start_timestamp,
                              end_timestamp=end_timestamp,
                              level=order_reader.level)

    # generate the annotation df
    order_reader.move_on(timeout=0)
    df = order_reader.data_df.copy()
    df = df[df.entity_id == entity_id].copy()
    if pd_is_not_null(df):
        df['value'] = df['order_price']
        df['flag'] = df['order_type'].apply(lambda x: order_type_flag(x))
        df['color'] = df['order_type'].apply(lambda x: order_type_color(x))
    print(df.tail())

    drawer = Drawer(main_df=kdata_reader.data_df, annotation_df=df)
    return drawer.draw_kline(show=False)
예제 #3
0
    def on_trading_close(self, timestamp):
        self.logger.debug('on_trading_close:{}'.format(timestamp))

        self.account.value = 0
        self.account.all_value = 0
        for position in self.account.positions:
            entity_type, _, _ = decode_entity_id(position.entity_id)
            data_schema = get_kdata_schema(entity_type,
                                           level=IntervalLevel.LEVEL_1DAY,
                                           adjust_type=self.adjust_type)

            kdata = get_kdata(provider=self.provider,
                              level=IntervalLevel.LEVEL_1DAY,
                              entity_id=position.entity_id,
                              order=data_schema.timestamp.desc(),
                              end_timestamp=timestamp,
                              limit=1,
                              adjust_type=self.adjust_type)

            closing_price = kdata['close'][0]

            position.available_long = position.long_amount
            position.available_short = position.short_amount

            if closing_price:
                if (position.long_amount
                        is not None) and position.long_amount > 0:
                    position.value = position.long_amount * closing_price
                    self.account.value += position.value
                elif (position.short_amount
                      is not None) and position.short_amount > 0:
                    position.value = 2 * (position.short_amount *
                                          position.average_short_price)
                    position.value -= position.short_amount * closing_price
                    self.account.value += position.value
            else:
                self.logger.warning(
                    'could not refresh close value for position:{},timestamp:{}'
                    .format(position['entity_id'], timestamp))

        # remove the empty position
        self.account.positions = [
            position for position in self.account.positions
            if position.long_amount > 0 or position.short_amount > 0
        ]

        self.account.all_value = self.account.value + self.account.cash
        self.account.closing = True
        self.account.timestamp = to_pd_timestamp(timestamp)

        self.logger.debug('on_trading_close:{},latest_account:{}'.format(
            timestamp, self.account))
        self.persist_account(timestamp)
예제 #4
0
    def on_trading_close(self, timestamp):
        self.logger.info('on_trading_close:{}'.format(timestamp))

        self.latest_account['value'] = 0
        self.latest_account['all_value'] = 0
        for position in self.latest_account['positions']:
            entity_type, _, _ = decode_entity_id(position['entity_id'])
            data_schema = get_kdata_schema(entity_type, level=self.level)

            kdata = get_kdata(provider=self.provider,
                              level=IntervalLevel.LEVEL_1DAY,
                              entity_id=position['entity_id'],
                              order=data_schema.timestamp.desc(),
                              end_timestamp=timestamp,
                              limit=1)

            closing_price = kdata['close'][0]

            position['available_long'] = position['long_amount']
            position['available_short'] = position['short_amount']

            if closing_price:
                if (position['long_amount']
                        is not None) and position['long_amount'] > 0:
                    position['value'] = position['long_amount'] * closing_price
                    self.latest_account['value'] += position['value']
                elif (position['short_amount']
                      is not None) and position['short_amount'] > 0:
                    position['value'] = 2 * (position['short_amount'] *
                                             position['average_short_price'])
                    position[
                        'value'] -= position['short_amount'] * closing_price
                    self.latest_account['value'] += position['value']
            else:
                self.logger.warning(
                    'could not refresh close value for position:{},timestamp:{}'
                    .format(position['entity_id'], timestamp))

        # remove the empty position
        self.latest_account['positions'] = [
            position for position in self.latest_account['positions']
            if position['long_amount'] > 0 or position['short_amount'] > 0
        ]

        self.latest_account['all_value'] = self.latest_account[
            'value'] + self.latest_account['cash']
        self.latest_account['closing'] = True
        self.latest_account['timestamp'] = to_pd_timestamp(timestamp)

        self.logger.info('on_trading_close:{},latest_account:{}'.format(
            timestamp, self.latest_account))
        self.persist_account(timestamp)
예제 #5
0
    def on_trading_close(self, timestamp):
        self.logger.info('on_trading_close:{}'.format(timestamp))
        # remove the empty position
        self.account.positions = [
            position for position in self.account.positions
            if position.long_amount > 0 or position.short_amount > 0
        ]

        # clear the data which need recomputing
        the_id = '{}_{}'.format(self.trader_name,
                                to_time_str(timestamp, TIME_FORMAT_ISO8601))

        self.account.value = 0
        self.account.all_value = 0
        for position in self.account.positions:
            entity_type, _, _ = decode_entity_id(position.entity_id)
            data_schema = get_kdata_schema(entity_type,
                                           level=IntervalLevel.LEVEL_1DAY,
                                           adjust_type=self.adjust_type)

            kdata = get_kdata(provider=self.provider,
                              level=IntervalLevel.LEVEL_1DAY,
                              entity_id=position.entity_id,
                              order=data_schema.timestamp.desc(),
                              end_timestamp=timestamp,
                              limit=1,
                              adjust_type=self.adjust_type)

            closing_price = kdata['close'][0]

            position.available_long = position.long_amount
            position.available_short = position.short_amount

            if closing_price:
                if (position.long_amount
                        is not None) and position.long_amount > 0:
                    position.value = position.long_amount * closing_price
                    self.account.value += position.value
                elif (position.short_amount
                      is not None) and position.short_amount > 0:
                    position.value = 2 * (position.short_amount *
                                          position.average_short_price)
                    position.value -= position.short_amount * closing_price
                    self.account.value += position.value

                # refresh profit
                position.profit = (closing_price - position.average_long_price) \
                                  * position.long_amount
                position.profit_rate = position.profit / (
                    position.average_long_price * position.long_amount)

            else:
                self.logger.warning(
                    'could not refresh close value for position:{},timestamp:{}'
                    .format(position.entity_id, timestamp))

            position.id = '{}_{}_{}'.format(
                self.trader_name, position.entity_id,
                to_time_str(timestamp, TIME_FORMAT_ISO8601))
            position.timestamp = to_pd_timestamp(timestamp)
            position.account_stats_id = the_id

        self.account.id = the_id
        self.account.all_value = self.account.value + self.account.cash
        self.account.closing = True
        self.account.timestamp = to_pd_timestamp(timestamp)
        self.account.profit = (
            self.account.all_value -
            self.account.input_money) / self.account.input_money

        self.session.add(self.account)
        self.session.commit()
        account_info = f'on_trading_close,holding size:{len(self.account.positions)} profit:{self.account.profit} input_money:{self.account.input_money} ' \
                       f'cash:{self.account.cash} value:{self.account.value} all_value:{self.account.all_value}'
        self.logger.info(account_info)