# Path: fooltrader/api/esapi/esapi.py
# def es_get_subscription(user_id=None, security_id=None, from_idx=0, size=500):
# def es_get_latest_daily_user_statistic(user_id, main_chain='eos', security_id='cryptocurrency_contract_RAM-EOS'):
# def es_get_user_statistic(main_chain='eos', security_id='cryptocurrency_contract_RAM-EOS', user_id=None,
#                           start_date=None, end_date=None, from_idx=0, size=100, order='volume'):
# def es_get_accounts(main_chain='eos', user_id=None, start_vol=None, end_vol=None, from_idx=0, size=100,
#                     order='totalEos', fields=None):
# def es_get_kdata(security_item, exchange=None, the_date=None, start_date=None, end_date=None, level='day', fields=None,
#                  from_idx=0, size=500, csv=False):
# def es_get_statistic(security_item, the_date=None, start_date=None, end_date=None, level='day',
#                      from_idx=0, size=500):
# 
# Path: fooltrader/domain/business/es_account.py
# class Account(DocType):
#     # 机器人名字
#     botName = Keyword()
#     # 可用现金
#     cash = Float()
#     # 具体仓位
#     positions = Nested()
#     # 市值
#     value = Float()
#     # 市值+cash
#     allValue = Float()
#     # 时间
#     timestamp = Date()
# 
#     # 收盘计算
#     closing = Boolean()
# 
#     class Meta:
#         index = 'account'
#         doc_type = 'doc'
#         all = MetaField(enabled=False)
#         dynamic = MetaField('strict')
# 
# class Position(DocType):
#     # 证券id
#     securityId = Keyword()
# 
#     # 做多数量
#     longAmount = Long()
#     # 可平多数量
#     availableLong = Long()
#     # 平均做多价格
#     averageLongPrice = Long()
# 
#     # 做空数量
#     shortAmount = Long()
#     # 可平空数量
#     availableShort = Long()
#     # 平均做空价格
#     averageShortPrice = Long()
# 
#     # 市值 或者 占用的保证金(方便起见，总是100%)
#     value = Float()
#     # 交易类型(0代表T+0,1代表T+1)
#     tradingT = Short()
# 
#     def __init__(self, meta=None, security_id=None, trading_t=1, **kwargs):
#         super().__init__(meta, **kwargs)
#         self.securityId = security_id
#         self.longAmount = 0
#         self.availableLong = 0
#         self.shortAmount = 0
#         self.availableShort = 0
# 
#         self.profit = 0
#         self.value = 0
#         self.tradingT = trading_t
# 
# Path: fooltrader/utils/es_utils.py
# 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_delete(index, query=None):
#     if query:
#         body = {"query": query}
#         es_client.delete_by_query(index=index, body=body)
#     else:
#         es_client.delete(index=index)
# 
# 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()
# 
# Path: fooltrader/utils/utils.py
# def fill_doc_type(doc_type, json_object):
#     for key in json_object:
#         doc_type[key] = json_object[key]


import logging
import math
from fooltrader.api.esapi import esapi
from fooltrader.domain.business.es_account import Account, Position
from fooltrader.utils.es_utils import es_get_latest_record, es_delete, es_index_mapping
from fooltrader.utils.utils import fill_doc_type
ORDER_TYPE_SHORT = 1
ORDER_TYPE_CLOSE_LONG = 2
ORDER_TYPE_CLOSE_SHORT = 3


class AccountService(object):

    def __init__(self, bot_name, timestamp,
                 base_capital=1000000,
                 buy_cost=0.001,
                 sell_cost=0.001,
                 slippage=0.001,
                 stock_fuquan='hfq'):
        self.logger = logging.getLogger(__name__)

        self.base_capital = base_capital
        self.buy_cost = buy_cost
        self.sell_cost = sell_cost
        self.slippage = slippage
        self.stock_fuquan = stock_fuquan
        self.bot_name = bot_name

        account = es_get_latest_record(index='account', query={"term": {"botName": bot_name}})

        if account:
            self.logger.warning("bot:{} has run before,old result would be deleted".format(bot_name))
            es_delete(index='account', query={"term": {"botName": bot_name}})

        es_index_mapping('account', Account)


# Path: fooltrader/api/esapi/esapi.py
# def es_get_subscription(user_id=None, security_id=None, from_idx=0, size=500):
# def es_get_latest_daily_user_statistic(user_id, main_chain='eos', security_id='cryptocurrency_contract_RAM-EOS'):
# def es_get_user_statistic(main_chain='eos', security_id='cryptocurrency_contract_RAM-EOS', user_id=None,
#                           start_date=None, end_date=None, from_idx=0, size=100, order='volume'):
# def es_get_accounts(main_chain='eos', user_id=None, start_vol=None, end_vol=None, from_idx=0, size=100,
#                     order='totalEos', fields=None):
# def es_get_kdata(security_item, exchange=None, the_date=None, start_date=None, end_date=None, level='day', fields=None,
#                  from_idx=0, size=500, csv=False):
# def es_get_statistic(security_item, the_date=None, start_date=None, end_date=None, level='day',
#                      from_idx=0, size=500):
# 
# Path: fooltrader/domain/business/es_account.py
# class Account(DocType):
#     # 机器人名字
#     botName = Keyword()
#     # 可用现金
#     cash = Float()
#     # 具体仓位
#     positions = Nested()
#     # 市值
#     value = Float()
#     # 市值+cash
#     allValue = Float()
#     # 时间
#     timestamp = Date()
# 
#     # 收盘计算
#     closing = Boolean()
# 
#     class Meta:
#         index = 'account'
#         doc_type = 'doc'
#         all = MetaField(enabled=False)
#         dynamic = MetaField('strict')
# 
# class Position(DocType):
#     # 证券id
#     securityId = Keyword()
# 
#     # 做多数量
#     longAmount = Long()
#     # 可平多数量
#     availableLong = Long()
#     # 平均做多价格
#     averageLongPrice = Long()
# 
#     # 做空数量
#     shortAmount = Long()
#     # 可平空数量
#     availableShort = Long()
#     # 平均做空价格
#     averageShortPrice = Long()
# 
#     # 市值 或者 占用的保证金(方便起见，总是100%)
#     value = Float()
#     # 交易类型(0代表T+0,1代表T+1)
#     tradingT = Short()
# 
#     def __init__(self, meta=None, security_id=None, trading_t=1, **kwargs):
#         super().__init__(meta, **kwargs)
#         self.securityId = security_id
#         self.longAmount = 0
#         self.availableLong = 0
#         self.shortAmount = 0
#         self.availableShort = 0
# 
#         self.profit = 0
#         self.value = 0
#         self.tradingT = trading_t
# 
# Path: fooltrader/utils/es_utils.py
# 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_delete(index, query=None):
#     if query:
#         body = {"query": query}
#         es_client.delete_by_query(index=index, body=body)
#     else:
#         es_client.delete(index=index)
# 
# 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()
# 
# Path: fooltrader/utils/utils.py
# def fill_doc_type(doc_type, json_object):
#     for key in json_object:
#         doc_type[key] = json_object[key]


# Path: fooltrader/bot/action/account_action.py
import logging
import math
from fooltrader.api.esapi import esapi
from fooltrader.domain.business.es_account import Account, Position
from fooltrader.utils.es_utils import es_get_latest_record, es_delete, es_index_mapping
from fooltrader.utils.utils import fill_doc_type

ORDER_TYPE_SHORT = 1
ORDER_TYPE_CLOSE_LONG = 2
ORDER_TYPE_CLOSE_SHORT = 3


class AccountService(object):

    def __init__(self, bot_name, timestamp,
                 base_capital=1000000,
                 buy_cost=0.001,
                 sell_cost=0.001,
                 slippage=0.001,
                 stock_fuquan='hfq'):
        self.logger = logging.getLogger(__name__)

        self.base_capital = base_capital
        self.buy_cost = buy_cost
        self.sell_cost = sell_cost
        self.slippage = slippage
        self.stock_fuquan = stock_fuquan
        self.bot_name = bot_name

        account = es_get_latest_record(index='account', query={"term": {"botName": bot_name}})

        if account:
            self.logger.warning("bot:{} has run before,old result would be deleted".format(bot_name))
            es_delete(index='account', query={"term": {"botName": bot_name}})

        es_index_mapping('account', Account)


        self.account = Account()