class NotifyEventBot(EventBot):
    def after_init(self):
        pass

    def __init__(self, security_id=None):
        self.notify_weixin = False
        self.notify_email = False

        super().__init__(security_id)

        if self.notify_weixin:
            self.weixin_action = WeixinAction()
        if self.notify_email:
            self.email_action = EmailAction()

        self.after_init() def get_es_kdata_index(security_type='stock', exchange='sh', level='day'):
    # 按 类型_国家_级别 来索引
    if exchange in ['sh', 'sz']:
        return '{}_{}_{}_kdata'.format(security_type, 'china', level)
    elif exchange in ['nasdaq', 'amex', 'nyse']:
        return '{}_{}_{}_kdata'.format(security_type, 'usa', level)
    else:
        return '{}_{}_{}_kdata'.format(security_type, exchange, level) def get_es_statistic_index(security_type='stock', exchange='sh', level='day'):
    # 按 类型_国家_级别 来索引
    if exchange in ['sh', 'sz']:
        return '{}_{}_{}_statistic'.format(security_type, 'china', level)
    elif exchange in ['nasdaq', 'amex', 'nyse']:
        return '{}_{}_{}_statistic'.format(security_type, 'usa', level)
    else:
        return '{}_{}_{}_statistic'.format(security_type, exchange, level) class CommonKData(BaseDocType):
    id = Keyword()
    timestamp = Date()
    updateTimestamp = Date()
    securityId = Keyword()
    code = Keyword()

    name = Keyword()
    open = Float()
    close = Float()
    high = Float()
    low = Float()
    volume = Float()
    turnover = Float()

    class Meta:
        doc_type = 'doc'
        all = MetaField(enabled=False)
        dynamic = MetaField('strict') class CommonStatistic(BaseDocType):
    id = Keyword()
    timestamp = Date()
    updateTimestamp = Date()
    securityId = Keyword()
    code = Keyword()
    name = Keyword()

    volume = Float()
    turnover = Float()
    flow = Float()
    flowIn = Float()
    flowOut = Float()
    bigFlowIn = Float()
    middleFlowIn = Float()
    smallFlowIn = Float()
    bigFlowOut = Float()
    middleFlowOut = Float()
    smallFlowOut = Float()

    class Meta:
        doc_type = 'doc'
        all = MetaField(enabled=False)
        dynamic = MetaField('strict') TIME_FORMAT_MICRO = "%Y%m%d %H%M%S.%f" def es_get_latest_timestamp(index, time_field='timestamp', query=None):
    latest_record = es_get_latest_record(index, time_field, query)
    if latest_record:
        return to_timestamp(latest_record['timestamp']) def es_get_latest_record(index, time_field='timestamp', query=None):
    body = '''
{
    "query": {
        "match_all": {}
    },
    "size": 1,
    "sort": [
        {
            "timestamp": {
                "order": "desc"
            }
        }
    ]
}
'''
    if time_field != 'timestamp':
        body = body.replace('timestamp', time_field)

    body = literal_eval(body)
    if query:
        body['query'] = query

    try:
        logger.info("search index:{},body:{}".format(index, body))
        response = es_client.search(index=index, body=body)
        if response['hits']['hits']:
            return response['hits']['hits'][0]['_source']
    except Exception as e:
        logger.warning(e)
    return None def es_index_mapping(index_name, doc_type, force=False):
    # 创建索引
    index = Index(index_name)
    index.doc_type(doc_type)

    if not index.exists():
        index.create()
    else:
        if force:
            index.upgrade() def to_timestamp(the_time):
    if type(the_time) == int:
        the_time = the_time / 1000.0

    if type(the_time) == float:
        return pd.Timestamp.fromtimestamp(the_time)

    return pd.Timestamp(the_time) def to_time_str(the_time, time_fmt=TIME_FORMAT_DAY):
    try:
        if time_fmt == TIME_FORMAT_MICRO:
            return to_timestamp(the_time).strftime(time_fmt)[0:-3]
        else:
            return to_timestamp(the_time).strftime(time_fmt)
    except Exception as e:
        return the_time def fill_doc_type(doc_type, json_object):
    for key in json_object:
        doc_type[key] = json_object[key] def is_same_date(one, two):
    return to_timestamp(one).date() == to_timestamp(two).date() def is_same_time(one, two):
    return to_timestamp(one) == to_timestamp(two)
from datetime import timedelta, datetime
from fooltrader.bot.bot import NotifyEventBot
from fooltrader.contract.es_contract import get_es_kdata_index, get_es_statistic_index
from fooltrader.domain.data.es_quote import CommonKData, CommonStatistic
from fooltrader.settings import TIME_FORMAT_MICRO
from fooltrader.utils.es_utils import es_get_latest_timestamp, es_get_latest_record, es_index_mapping
from fooltrader.utils.utils import to_timestamp, to_time_str, fill_doc_type, is_same_date, is_same_time
import pandas as pd
# -*- coding: utf-8 -*-



statistic_index_name = get_es_statistic_index(security_type='cryptocurrency', exchange='contract')
kdata_index_name = get_es_kdata_index(security_type='cryptocurrency', exchange='contract', level='1min')

es_index_mapping(statistic_index_name, CommonStatistic)
es_index_mapping(kdata_index_name, CommonKData)


class EosStatisticBot(NotifyEventBot):
    BIG_ORDER = 2000 * 10000
    MIDDLE_ORDER = 500 * 10000

    def on_init(self):
        super().on_init()
        self.security_id = 'cryptocurrency_contract_RAM-EOS'

        query = {
            "term": {"securityId": ""}
        }
        query["term"]["securityId"] = self.security_id

        # get latest kdata timestamp
        latest_kdata_timestamp = es_get_latest_timestamp(index=kdata_index_name, query=query)

        # get latest eos statistic timestamp

        latest_statistic_record = es_get_latest_record(index=statistic_index_name,