#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import btcchinaData as btcDat
import LogPro
import dirUtil
import configRead
class DataTool():
    def __init__(self):
        self.logObj = LogPro.LogPro()
        self.marketNowID = 0   #当前成交id
        self.oldDataLastID = 0
        self.newDataStartID = 0
        self.newDataStartTime = 0 
        self.newData = []
        self.dataIDDic = {}
        self.lastCount = 0
        self.firstNone = 0
        self.lastNonestr = ''
        self.btcDatSer = btcDat.BTCChinaData()
        self.lastServerTime = 0
        #当前买卖挂单
        self.orderBuy5 = []
        self.orderSell5 = []
        self.getOrderTime = 0
        self.prompt = {}
        #数据分析部分
        self.StartTime = int(time.time())#自动开始交易等待时间来1分钟
        self.lastType = 'sell'
        #{'access_key':access_key,'secret_key':secret_key,'step_price':step_price,'step_num':step_num,'force_sellpecent':force_sellpecent,'istest':bool(istest),'tbase_cny':tbase_cny,'tbase_btc':tbase_btc}
        self.netConfig = configRead.getConfigDic()
        print self.netConfig
        #对买卖挂单数据的分析
        self.netPrices = []
        self.netStep = self.netConfig['step_price']  #网络简距设置为0.5元
        self.lastMarketPrice = 0.0
        self.baseBuySell = self.netConfig['step_num'] #单次交易数量
        self.tcny = self.netConfig['tbase_cny'] #交易测试原始资金
        self.tbtc = self.netConfig['tbase_btc'] #交易测试原始btc
        self.forceSellPecent = self.netConfig['force_sellpecent']
        self.resCny = self.tcny#总资产
        self.marketTimes = 0 #交易次数
        self.marketBuyTimes = 0#交易次数中买次数
        self.marketSellTimes = 0#交易中卖次数
        self.noCny = False #价格已经下跌到无资金支持的情况了
    def getNetLen(self):
        return len(self.netPrices)
    def getNowPriceWithNumber(self,bstype,number = 0.001):
        if bstype == 'buy':
            if len(self.orderSell5) == 0:
                return None
            if self.orderSell5[4]['totalamount'] >= number:
                return self.orderSell5[4]['price']
            elif self.orderSell5[4]['totalamount'] + self.orderSell5[3]['totalamount'] >= number:
                return self.orderSell5[3]['price']
            elif self.orderSell5[4]['totalamount'] + self.orderSell5[3]['totalamount'] + self.orderSell5[2]['totalamount'] >= number:
                return self.orderSell5[2]['price']
            elif self.orderSell5[4]['totalamount'] + self.orderSell5[3]['totalamount'] + self.orderSell5[2]['totalamount'] + self.orderSell5[1]['totalamount']>= number:
                return self.orderSell5[1]['price']
            elif self.orderSell5[4]['totalamount'] + self.orderSell5[3]['totalamount'] + self.orderSell5[2]['totalamount'] + self.orderSell5[1]['totalamount'] + self.orderSell5[0]['totalamount']>= number:
                return self.orderSell5[0]['price']
            else:
                return self.orderSell5[0]['price'] 
        elif bstype == 'sell':
            if len(self.orderBuy5) == 0:
                return None
            if self.orderBuy5[0]['totalamount'] >= number:
                return self.orderBuy5[0]['price']
            elif self.orderBuy5[0]['totalamount'] + self.orderBuy5[1]['totalamount'] >= number:
                return self.orderBuy5[1]['price']
            elif self.orderBuy5[0]['totalamount'] + self.orderBuy5[1]['totalamount'] + self.orderBuy5[2]['totalamount'] >= number:
                return self.orderBuy5[2]['price']
            elif self.orderSell5[0]['totalamount'] + self.orderBuy5[1]['totalamount'] + self.orderBuy5[2]['totalamount'] + self.orderBuy5[3]['totalamount']>= number:
                return self.orderBuy5[3]['price']
            elif self.orderBuy5[0]['totalamount'] + self.orderBuy5[1]['totalamount'] + self.orderBuy5[2]['totalamount'] + self.orderBuy5[3]['totalamount'] + self.orderBuy5[4]['totalamount'] >= number:
                return self.orderBuy5[4]['price']
            else:
                return self.orderBuy5[0]['price']
    def setOrder5(self,marketorder):
        #{"grouporder": {"ask": [{"totalamount": 5, "price": 1705.99, "type": "ask"}, {"totalamount": 3.4873, "price": 1705.29, "type": "ask"}, {"totalamount": 4.1, "price": 1704.74, "type": "ask"}, {"totalamount": 0.1586, "price": 1704.73, "type": "ask"}, {"totalamount": 0.0733, "price": 1704.34, "type": "ask"}], "bid": [{"totalamount": 0.1427, "price": 1704.07, "type": "bid"}, {"totalamount": 0.966, "price": 1704.06, "type": "bid"}, {"totalamount": 0.081, "price": 1704.05, "type": "bid"}, {"totalamount": 0.02, "price": 1703.87, "type": "bid"}, {"totalamount": 1.4308, "price": 1703.76, "type": "bid"}], "market": "btccny"}}
        self.orderBuy5 = marketorder['grouporder']['bid']
        self.orderSell5 = marketorder['grouporder']['ask']
        self.getOrderTime = int(time.time())
        if self.lastMarketPrice > 1:
            return self.addOrderBuyAndSell()
        else:
            print 'lastmarketprice none'
            return 'none',None,None
    def addOrderBuyAndSell(self):
        pricebuyx = self.getNowPriceWithNumber('buy', self.baseBuySell)
        pricesellx = self.getNowPriceWithNumber('sell', self.baseBuySell)
        savestr = '{\"buyorder\":%.2f,\"sellorder\":%.2f,\"date\":%d}\n'%(pricebuyx,pricesellx,int(time.time()))
        self.savelog(savestr, 'buysellorder.txt')
        print 'priceBS',pricebuyx,pricesellx
        bstype,pricetmp,numtmp = self.findPriceInNetAndBuySell(pricebuyx, pricesellx)
        return bstype,pricetmp,numtmp
    def findPriceInNetAndBuySell(self,mybuy,mysell):
        if len(self.netPrices) == 0:
            dirUtil.saveDatToFile('net self.netPrices empty\n','netbuyselllog.txt')
            self.buy(mybuy,mysell,self.baseBuySell)
            return 'none',None,None
        else:
            si = -1
            lastprice = self.netPrices[len(self.netPrices)-1]
            if lastprice - mybuy > self.netStep:
                print lastprice,mybuy
                self.buy(lastprice - self.netStep,mysell,self.baseBuySell) #阶格下跌一个网络，进行买入操作
                return 'buy',lastprice + self.netStep,self.baseBuySell
            elif mysell - lastprice > self.netStep:
                for i in range(len(self.netPrices)):
                    if mysell > self.netPrices[i]:
                        si = i
                num = (len(self.netPrices) - si)*self.baseBuySell
                self.sell(mysell,si,num)
                return 'sell',mysell,num
    def getResCny(self):
        self.resCny = self.tbtc*self.lastMarketPrice + self.tcny
        return self.resCny
    def buy(self,price,mysell,num = 0.001):
        if self.tcny > price*num:
            self.tbtc += num
            self.tcny -= price*num
            self.resCny = self.getResCny()
            self.marketTimes += 1
            self.marketBuyTimes += 1
            self.netPrices.append(price)
            self.noCny = False
            print 'len self.netprices',len(self.netPrices)
            dirUtil.saveDatToFile('{buy:%.2f,num:%.3f,res:%.2f,btc:%.3f,cny:%.2f,nowPrice:%.2f,times:%d,buytimes:%d,selltimes:%d}--%s\n'%(price,num,self.resCny,self.tbtc,self.tcny,self.lastMarketPrice,self.marketTimes,self.marketBuyTimes,self.marketSellTimes,str(self.netPrices)),'netbuyselllog.txt')
        else:
            #现在资金已经不能支持币价下跌了，这时可以以现价卖出最上层的一个网络币以预防价格下跌,如果价格再下跌，则下次可以再买一个回来。
            nx = int(len(self.netPrices)*self.forceSellPecent)
            self.netPrices = self.netPrices[nx:]
            self.sell(mysell,self.baseBuySell*nx,False)
    def sell(self,price,n,num = 0.001,selltype = True):
        if selltype:
            if n < 0:
                dirUtil.saveDatToFile('net sell erro\n','netbuyselllog.txt')
                return
            self.tbtc -= num
            self.tcny += price*num
            self.resCny = self.getResCny()
            self.marketTimes += 1
            self.marketSellTimes += 1
            self.netPrices = self.netPrices[:n]
            self.noCny = False
            dirUtil.saveDatToFile('{type:nomal,sell:%.2f,num:%.3f,res:%.2f,btc:%.3f,cny:%.2f,nowPrice:%.2f,times:%d,buytimes:%d,selltimes:%d}--%s\n'%(price,num,self.resCny,self.tbtc,self.tcny,self.lastMarketPrice,self.marketTimes,self.marketBuyTimes,self.marketSellTimes,str(self.netPrices)),'netbuyselllog.txt')
        else:
            self.tbtc -= num
            self.tcny += price*num
            self.resCny = self.getResCny()
            self.marketTimes += 1
            self.marketSellTimes += 1
            self.noCny = True
            dirUtil.saveDatToFile('{type:nobuy,sell:%.2f,num:%.3f,res:%.2f,btc:%.3f,cny:%.2f,nowPrice:%.2f,times:%d,buytimes:%d,selltimes:%d}--%s\n'%(price,num,self.resCny,self.tbtc,self.tcny,self.lastMarketPrice,self.marketTimes,self.marketBuyTimes,self.marketSellTimes,str(self.netPrices)),'netbuyselllog.txt')
      
    def _saveDatTOfileWith15000Dat(self):
        if len(self.newData) > 15000:
            saveDats = self.newData[0:len(self.newData)-5000]
            timestr = int(time.time())
            f = open(str(timestr)+'.txt','w')
            f.write(str(saveDats))
            f.close()
            print 'save 1500 data'
            self.newData = self.newData[len(self.newData)-5000:]
            self.dataIDDic.clear()
            for da in self.newData:
                self.dataIDDic[da['trade_id']] = da
            print 'datatoo line 117'
    def addNewData(self,tradeData):
        #data类型:{"price": 1704.34, "trade_id": 36408115, "amount": 0.01, "date": 1437383495, "type": "buy", "market": "btccny"}
        #self.logObj.funcRunLog('DataTool.addNewData start')
        self.lastServerTime = int(tradeData['date'])
        self.newData.append(tradeData)
        self.dataIDDic[tradeData['trade_id']] = tradeData
        if len(self.newData) > 15000:
            self._saveDatTOfileWith15000Dat()
        self.prompt['nowprice'] = tradeData['price']
        self.prompt['nownumber'] = tradeData['amount']
        self.prompt['nowid'] = tradeData['trade_id']
        self.prompt['nowtype'] = tradeData['type']
        self.lastMarketPrice = tradeData['price']
        print self.lastMarketPrice
        self.resCny = self.tbtc*tradeData['price'] + self.tcny
        return self.prompt
    def savelog(self,strlog,filename = 'datalog.txt'):
        dirUtil.saveDatToFile(strlog, filename)
