Ejemplo n.º 1
0
 def pause_buy_DEL(self,
                   priceitem,
                   pause_seconds,
                   pause_seconds_stop_lost=0):
     pause_finish = None
     if self.__pause_start_time is None and pause_seconds > self.__DEFAULT_BUY_PAUSE_SECONDS:
         # 暂停开始时间,只设置一次,然后开始检查,直到暂停结果
         self.__pause_start_time = datetime.datetime.now()
         # 已经开始暂停了,但是还没有结束
         pause_finish = False
         if pause_seconds > self.__DEFAULT_BUY_PAUSE_SECONDS and pause_seconds_stop_lost == 0:
             print('{0}: {1}买入暂停,由于超过一半的比例,暂停{2}秒!'.format(
                 common.get_curr_time_str(), priceitem.coin, pause_seconds))
         elif pause_seconds_stop_lost > 0:
             print('{0}: {1}买入暂停,由于进行了止损操作,暂停{2}秒!'.format(
                 common.get_curr_time_str(), priceitem.coin, pause_seconds))
     if self.__pause_start_time is not None:
         currtime = datetime.datetime.now()
         diff = currtime - self.__pause_start_time
         diffseconds = diff.seconds
         if diffseconds > pause_seconds:
             # 暂停结束
             self.__pause_start_time = None
             pause_finish = True
             self.__pause_seconds_stop_lost = 0
             if pause_seconds > self.__DEFAULT_BUY_PAUSE_SECONDS:
                 print('{0}: {1}买入暂停结束,共暂停{2}秒!'.format(
                     common.get_curr_time_str(), priceitem.coin,
                     pause_seconds))
         else:
             pause_finish = False
     return pause_finish
Ejemplo n.º 2
0
 def getprice(self, market, coin_pair):
     try:
         order_market = ordermanage.OrderManage(market)
         price_depth = order_market.getMarketDepth(coin_pair)
         buy_depth = 0
         sell_depth = 0
         priceitem = None
         coin = coin_pair.split('_')[0]
         # use the sell price as buy_price
         buy_price = price_depth.sell[0][0]
         # use the buy orderprice as sell price
         sell_price = price_depth.buy[0][0]
         # 尝试列表中所有的买入和
         for buy_item in price_depth.buy:
             buy_depth = buy_depth + buy_item[1]
         for sell_item in price_depth.sell:
             sell_depth = sell_depth + sell_item[1]
         buy_depth = round(buy_depth, 2)
         sell_depth = round(sell_depth, 2)
         # 把价格日期保存成字符串
         priceitem = priceupdate.PriceItem(common.get_curr_time_str(),
                                           coin_pair, buy_price, buy_depth,
                                           sell_price, sell_depth)
         # result = {"market":market, "coin_pair": coin_pair}
         result = '{0},{1},{2},{3},{4},{5},{6}\n'.format(
             market, coin_pair, common.get_curr_time_str(), buy_price,
             buy_depth, sell_price, sell_depth)
     except Exception as e:
         print('取得[{1}]价格列表时错误:{0}'.format(str(e), coin_pair))
         return None
     return result
Ejemplo n.º 3
0
 def pause_buy_new(self, priceitem, pause_seconds, pause_comments):
     # 暂停判断,检查是否需要暂停
     if self.pause_status is False:
         if pause_seconds > self.__DEFAULT_BUY_PAUSE_SECONDS:
             self.__pause_seconds = pause_seconds
             # 暂停开始时间,只设置一次,然后开始检查,直到暂停结果
             self.__pause_start_time = datetime.datetime.now()
             self.pause_status = True
             print('{0}: [{1}]暂停,暂停[{2}]秒,原因[{3}]!'.format(
                 common.get_curr_time_str(), priceitem.coin, pause_seconds,
                 pause_comments))
     elif self.pause_status is True:
         currtime = datetime.datetime.now()
         diff = currtime - self.__pause_start_time
         diffseconds = diff.seconds
         # 暂停结束
         if diffseconds > self.__pause_seconds:
             self.pause_status = False
             self.__pause_start_time = None
             self.__pause_seconds = 0
             print('{0}: [{1}]暂停结束]!'.format(common.get_curr_time_str(),
                                             priceitem.coin))
         pass
     return self.pause_status
     pass
Ejemplo n.º 4
0
    def update_order_status(self):
        order_list = ormmysql.openorderlist()
        for orderitem in order_list:
            if orderitem.buy_status == const.ORDER_STATUS_OPEN:
                order_status = self.order_market.getOrderStatus(orderitem.buy_order_id, orderitem.priceitem.coin)
                # 处理状态取值时错误的情况
                if order_status is None:
                    continue
                orderitem.buy_status = order_status
                ormmysql.updateorder(orderitem)
            if orderitem.sell_status == const.ORDER_STATUS_OPEN:
                order_status = self.order_market.getOrderStatus(orderitem.sell_order_id, orderitem.priceitem.coin)
                # 处理状态取值时错误的情况
                if order_status is None:
                    continue
                orderitem.sell_status = order_status
                ormmysql.updateorder(orderitem)
                if order_status == const.ORDER_STATUS_CLOSED:
                    orderitem.sell_date = common.get_curr_time_str()
                    ormmysql.updateorder(orderitem)
                    # 把交易记录从交易表转移到LOG表
                    ormmysql.delorder(orderitem)
                    profit_amount = round(orderitem.sell_amount - orderitem.buy_amount,10)
                    print('{0}:[{1}]{smile}已经成功交易,盈利{2}! BuyPrice:{3}, SellPrice:{4}, ProfiteRate:{5}'.format(\
                            common.get_curr_time_str(), orderitem.priceitem.coin, profit_amount, orderitem.buy_price, orderitem.sell_price,\
                            publicparameters.SELL_PROFIT_RATE, smile='^_^ '*5))

                    # the sell status is closed to move log table
            # 这里会导致出问题,出现上面更新后又再次删除的情况
            # if orderitem.sell_status == const.ORDER_STATUS_CLOSED:
            #     # 把交易记录从交易表转移到LOG表
            #     ormmysql.delorder(orderitem)
        pass
Ejemplo n.º 5
0
def gen_money_summary():
    # 市场的交易处理器
    order_market = ordermanage.OrderManage('btc38')
    # 所有的余额
    mybal = order_market.getMyBalance()
    mybaldate = common.get_curr_time_str()
    # 计算当前时间的评估价格
    currallprice_btc = order_market.getMarketPrice('all_btc')
    currallprice_cny = order_market.getMarketPrice('all_bitcny')
    currallprice_usd = order_market.getMarketPrice('all_usdt')

    total_bal_cny = 0
    # RMB价格
    btcprice_cny = currallprice_cny.get('btc').get('ticker').get('buy')
    # USD价格
    btcprice_usd = currallprice_usd.get('btc').get('ticker').get('buy')
    for coin in mybal:
        coinbal = mybal.get(coin).get('available') + mybal.get(coin).get(
            'locked')
        if coinbal == 0:
            continue
        if coin == 'bitcny':
            total_bal_cny = total_bal_cny + coinbal
            pass
        elif coin == 'usdt':
            # 把USD转换成btc后再转换成cny来计算
            total_bal_cny = total_bal_cny + coinbal / btcprice_usd * btcprice_cny
            pass
        elif coin == 'btc':
            total_bal_cny = total_bal_cny + coinbal * btcprice_cny
        else:
            # btc定价的价格
            try:
                if currallprice_btc.get(coin) is not None:
                    coinprice_btc = currallprice_btc.get(coin).get(
                        'ticker').get('buy')
                    # 转换成btc的数量
                    coinbal_btc = coinbal * coinprice_btc
                    # 转换成RMB的价格
                    total_bal_cny = total_bal_cny + coinbal_btc * btcprice_cny
                else:
                    # 对于没有btc定价的币种则用bitcny来查找计算余额
                    coinprice_cny = order_market.getMarketPrice(
                        coin + '_bitcny').get('ticker').get('buy')
                    total_bal_cny = total_bal_cny + coinbal * coinprice_cny
            except Exception as e:
                # 不再支持交易的coin
                if coin == 'ybc' or coin == 'nss':
                    pass
                else:
                    print('{0} price error:{1}'.format(coin, str(e)))
    total_bal_cny = round(total_bal_cny, 2)
    print('{0}: balance_cny: {1}'.format(mybaldate, total_bal_cny))
    # 保存结果到文件
    balfile = open(summary_file, 'a')
    mybalancesummary = '{0}:{1}\n'.format(mybaldate, total_bal_cny)
    balfile.write(mybalancesummary)
    balfile.close()
    return total_bal_cny
    pass
Ejemplo n.º 6
0
 def get_warning_message(self, chg_info):
     coin_pair = chg_info.get('coin_pair')
     chg_percent = round(chg_info.get('percent') * 100, 2)
     begin_price = chg_info.get('begin')
     end_price = chg_info.get('end')
     begin_depth = round(chg_info.get('depth_begin'), 0)
     end_depth = round(chg_info.get('depth_end'), 0)
     message = '[{0}]:change percent [{1}%] @{2},[{3}] hour ago,Price[{4}->{5}] Buy Depth[{6}->{7}]'
     message =message.format(coin_pair, chg_percent, common.get_curr_time_str(), \
                             self.__alert_duration,begin_price,end_price, begin_depth, end_depth )
     message = message + config.sms_auth.get('signature')
     return message
     pass
Ejemplo n.º 7
0
    def big_fish_process(self):
        each_big_fish_list = self.bigfish.get_big_fish_list()
        # 取每次列表的中第一个列表
        if len(each_big_fish_list) > 0:
            self.big_fish_list = self.big_fish_list + each_big_fish_list[0]
        print('big fish list of all: {0}'.format(self.big_fish_list))
        # big fish 列表写入
        if len(each_big_fish_list) != 0:
            bigfishfile = open('bigfish.txt', 'a')
            bigfishfile.write('{0}:{1}\n'.format(common.get_curr_time_str(),
                                                 each_big_fish_list))
            bigfishfile.close()

        pass
Ejemplo n.º 8
0
    def getMarketDepth(self, coin_code, mk_type='btc'):
        try:
            data = self.btcwexclt.getDepth(mk_type, coin_code)
            # 买单列表
            buylist = list(data.get(coin_code + '_' + mk_type).get('bids'))
            # 卖单列表
            selllist = list(data.get(coin_code + '_' + mk_type).get('asks'))

            depthlist = common.JSONObject({
                'date': common.get_curr_time_str(),
                'sell': selllist,
                'buy': buylist
            })
        except Exception as e:
            # print(str(e))
            depthlist = None
        return depthlist
Ejemplo n.º 9
0
    def output_forecast_list(self, market, coin_list):
        unsorted_forecast_list = []
        for coin_pair in coin_list:
            self.monitor_coin(market, coin_pair)
            forecast_list = self.__pricebuffer_list.get(
                coin_pair).price_forecast_list
            verified_count = 0
            for forecast_item in forecast_list:
                if forecast_item.price_buy_forecast_verify is True:
                    verified_count = verified_count + 1
            if len(forecast_list) == 0:
                rate = 0
            else:
                rate = round(verified_count / len(forecast_list), 2)
            unsorted_forecast_list.append({'coin':coin_pair, 'total':len(forecast_list), 'verified':verified_count, \
                                         'rate': rate })
        # 对验证的结果进行排序,按验证率进行倒序
        sorted_forecast_list = sorted(unsorted_forecast_list,
                                      key=operator.itemgetter('rate'),
                                      reverse=True)

        print('---------------------final resut:--------------------')
        for forecast_item in sorted_forecast_list:
            if forecast_item.get('rate') > 0:
                # Save to file to do analyze
                forecasedata = open('ForecaseData.txt', 'a')

                data = '{0}: coin:{1}, verified:{2}, forecase-total:{3}, rate:{4}\n'.format(\
                      common.get_curr_time_str(), forecast_item.get('coin'), \
                         forecast_item.get('verified'), forecast_item.get('total'), forecast_item.get('rate') )
                print(data)
                # save to file
                forecasedata.write(data)
                forecasedata.close()

            pass
        return sorted_forecast_list
Ejemplo n.º 10
0
    def buyforecast_verify(self, newpriceitem):
        if len(self.price_buffer) == 0:
            newpriceitem.price_buy_forecast_verify = False
            return
        # 判断当前之前一段时间的预测买入是不是达到了卖出条件,如果达到说明预期结果正确
        endtime = common.CommonFunction.strtotime(newpriceitem.pricedate)
        starttime = endtime - datetime.timedelta(
            seconds=self.__PRICE_TREND_RANGE)
        for priceitem in self.price_buffer:
            pricedate = common.CommonFunction.strtotime(priceitem.pricedate)
            if pricedate > starttime and pricedate < endtime and priceitem.coin == newpriceitem.coin:
                # 已经预测过且得到验证的则不需要再继续进行
                if priceitem.price_buy_forecast_verify is True or priceitem.price_buy_forecast is False:
                    continue
                actual_profit_rate = (
                    newpriceitem.buy_price -
                    priceitem.buy_price) / priceitem.buy_price
                # 达到卖出条件则认为预测成功,预测价格变化是实际的一定比例,如0.8
                if actual_profit_rate > publicparameters.SELL_PROFIT_RATE * 0.9:
                    priceitem.price_buy_forecast_verify = True
                    priceitem.price_buy_forecast_verify_date = common.get_curr_time_str(
                    )
                    # print('Verified passed:{0}:coin:{1},buy_price:{2},sell_price:{3}'.format(\
                    #     common.get_curr_time_str(),priceitem.coin,priceitem.buy_price,newpriceitem.buy_price))
                    # print('Verified result is correct: @%f'% newpriceitem.buy_price)
                    priceinfo = self.__save_price(priceitem)
                    # 执行实际的卖出操作
                    # sell to process in sell_check for all transaction
                    # trans_status = self.cointrans_handler.coin_trans(self.market, 'sell', newpriceitem.buy_price, priceitem)
                    trans_comments = "{0} -->Done: Verified Date: {1}"
                    # 打印出交易信息
                    # print(trans_comments.format(priceinfo, common.get_curr_time_str()))
                    # print(priceinfo+'-->Done: trans status: @%s'%common.CommonFunction.get_curr_time())
                else:
                    priceitem.price_buy_forecast_verify = False

        pass
Ejemplo n.º 11
0
 def stop_lost(self, curr_pricitem):
     stop_lost_status = False
     open_order_list = ormmysql.openorderlist()
     for open_order in open_order_list:
         # 如果当前价格和买入价格小于止损的比例,则执行先取消订单再按当前价格的直接卖出操作
         curr_price = curr_pricitem.sell_price
         if curr_price / open_order.buy_price < (
                 1 - publicparameters.STOP_LOST_RATE
         ) and curr_pricitem.coin == open_order.coin:
             # if curr_pricitem.coin == open_order.coin:
             status = self.cointrans_handler.order_market.cancelOrder(
                 open_order.sell_order_id, coin_code=curr_pricitem.coin)
             # #  TEST usage
             # status = const.CANCEL_STATUS_SUCC
             if status == const.CANCEL_STATUS_FAIL:
                 pass
             elif status == const.CANCEL_STATUS_SUCC:
                 # 更新订单的状态为取消
                 # ormmysql.updateorder(open_order)
                 # 重新卖出,以当前价卖出进行止损
                 sell_status = self.cointrans_handler.coin_trans(
                     self.market, const.TRANS_TYPE_SELL, curr_price,
                     open_order.priceitem)
                 # #  test only
                 # sell_status = True
                 # 止损卖出成功
                 if sell_status is True:
                     print("-------:(--------订单进行了止损操作,coin:{0},操作时间:{1}".
                           format(open_order.coin,
                                  common.get_curr_time_str()))
                     stop_lost_status = True
                     pass
                 # 止损卖出失败,继续进行循环操作进行下一次的自动卖出
                 else:
                     pass
                 pass
     return stop_lost_status
Ejemplo n.º 12
0
    def coin_trans(self, market, trans_type, trans_price, price_item):
        coin = price_item.coin
        coin_pair = price_item.coin_pair
        # coin_pair = coin+'_btc'

        # 判断是不是满足交易的条件,不满足则退出不进行交易
        if trans_type == const.TRANS_TYPE_BUY:
            if self.check_trans_indi(coin_pair) is False:
                # print('{0}:不符合买入条件,可能是超过买入数量上限或者比例上限'.format(coin))
                return False

        # 对价格和交易单位进行rounding,否则有可能造成调用接口失败
        rounding_price = publicparameters.rounding_price(coin)
        rounding_unit = publicparameters.rounding_unit(coin)
        # 买入时的价格
        buy_price = price_item.buy_price
        # 交易UNITS
        mk_type = coin_pair.split('_')[1]
        # 不同的基础货币有不同的买入金额
        # trans_amount_per_trans = self.__regular_param.get('buy_amt').get(mk_type)
        trans_amount_per_trans = self.get_config_data(coin_pair, 'buy_amt')
        trans_units = round(trans_amount_per_trans / buy_price, rounding_unit)
        # 第一次交易卖出时的UNIT和买入UNIT会有一个0.5%的误差
        newtrans_units = trans_units
        # 对交易价格进行ROUNDING处理
        trans_price_rounding = round(trans_price, rounding_price)
        # 有些价格较贵,金额太小出现UNIT为0的情况,不需要再提交订单
        if trans_units < 0.00001:
            return False
        # 当前交易的对象
        if trans_type == const.TRANS_TYPE_BUY:
            orderitem = cointrans.OrderItem(market, coin_pair)
        elif trans_type == const.TRANS_TYPE_SELL:
            orderitem = cointrans.OrderItem(market, coin_pair)
            # 取得当前可以卖出的总units
            account_summary = ormmysql.get_regular_invest_summary(coin_pair)
            total_units = account_summary.get('unit_balance')
            trans_units = round(total_units, rounding_unit)

        # 交易的order_market
        order_market = self.order_market

        # 提交订单
        if trans_type == const.TRANS_TYPE_SELL:
            bal = order_market.getMyBalance(coin)
            # 可能出现余额不足的情况
            if bal > trans_units:
                pass
                # trans_order=common.JSONObject({'order_id':3333})
                trans_order = order_market.submitOrder(coin_pair, trans_type,
                                                       trans_price_rounding,
                                                       trans_units)
            # 处理第一次买入出现扣除手续费后卖出时余额不足的情况
            elif trans_units * 0.99 < bal:
                newtrans_units = round(trans_units * 0.99, rounding_unit)
                trans_order = order_market.submitOrder(coin_pair, trans_type,
                                                       trans_price_rounding,
                                                       newtrans_units)
            # 余额不足的取消卖出交易
            else:
                orderitem.sell_status = const.ORDER_STATUS_CANCEL
                # ormmysql.updateorder(orderitem)
                # ormmysql.delorder(orderitem)
                print('{0}:余额不足,已经取消订单'.format(coin))
                return False
        else:
            trans_order = order_market.submitOrder(coin_pair, trans_type,
                                                   trans_price_rounding,
                                                   trans_units)
        #     trans_units)
        # # 取得返回订单的信息
        order_id = trans_order.order_id
        if order_id == -1111111:
            order_status = 'fail'
            return False
        else:
            order_status = order_market.getOrderStatus(order_id, coin_pair)
            # 如果状态为None,说明取状态有异常,对于卖出默认为OPEN,防止出现多现卖出状态设置为None,继续卖出的情况
            if order_status is None:
                order_status = const.ORDER_STATUS_OPEN
        # 保留交易时的相关信息到orderitem对象中
        if trans_type == const.TRANS_TYPE_BUY:
            orderitem.buy_order_id = order_id
            orderitem.buy_status = order_status
            orderitem.buy_price = trans_price_rounding
            orderitem.buy_amount = trans_amount_per_trans
            orderitem.buy_units = trans_units
            orderitem.buy_date = common.get_curr_time_str()
            orderitem.priceitem = price_item
            # 买入时新增加一个订单,卖出时则直接更新已经存在的订单
            # 保存数据到DB
            ormmysql.save_regular_invest(orderitem)
            # ormmysql.saveorder(orderitem)
            print(
                '{0}:开始[{1}]交易,交易状态:{2}:PriceDate:{3},Coin:{4}, BuyPrice:{5}'.
                format(common.get_curr_time_str(), trans_type, order_status,
                       price_item.pricedate, price_item.coin,
                       price_item.buy_price))
        elif trans_type == const.TRANS_TYPE_SELL:
            orderitem.sell_order_id = order_id
            orderitem.sell_status = order_status
            orderitem.sell_price = trans_price_rounding
            orderitem.sell_amount = round(trans_units * trans_price_rounding,
                                          10)
            orderitem.sell_units = trans_units
            orderitem.sell_date = common.get_curr_time_str()
            ormmysql.save_regular_invest(orderitem)
            print(
                '{0}:开始[{1}]交易,交易状态:{2}:PriceDate:{3},Coin:{4}, BuyPrice:{5}, SellPrice:{6}, ProfiteRate:{7}'
                .format(common.get_curr_time_str(), trans_type, order_status,
                        price_item.pricedate, price_item.coin,
                        price_item.buy_price, orderitem.sell_price,
                        publicparameters.SELL_PROFIT_RATE))
            # 成功卖出后把所有的买入记录清空,保存在LOG表
            # 不需要保存到LOG,明细一直保留所有的记录

            # 更新到DB
            # ormmysql.updateorder(orderitem)
            # remove to log table if sell status is closed
            # if order_status == const.ORDER_STATUS_CLOSED:
            #     ormmysql.delorder(orderitem)

        return True
Ejemplo n.º 13
0
    def get_balance(self):
        all_market_bal = {}
        all_coin_list = []
        for market in self.__market_list:
            order_market = ordermanage.OrderManage(market)
            market_bal = order_market.getMyBalance()
            all_market_bal[market] = market_bal
            all_coin_list = all_coin_list + list(market_bal.keys())
        # 所有市场的COIN列表
        all_coin_list = list(set(all_coin_list))
        all_coin_bal = {}
        # 当前价格的评估总价
        total_est_cny = 0
        # 除了open order之外的当前价格评估
        total_est_cny_ori = 0
        # 总的open order buy amount
        total_open_buy_amt = 0
        # 总的open order 估算amount
        total_open_est_cny = 0
        # 所有COIN的明细余额
        open_bal_list = []
        currdate = common.get_curr_time_str()
        # 按币种循环生成各个市场的帐户的情况
        for coin in all_coin_list:
            # time.sleep(0.5)
            for market in self.__market_list:
                if coin in all_market_bal[market].keys():
                    coin_bal = all_market_bal[market][coin]['available']
                    coin_bal_lock = all_market_bal[market][coin]['locked']
                    if coin == 'cny':
                        total_cny_bal = round(coin_bal + coin_bal_lock, 4)
                        continue
                    coin_total_bal = round(coin_bal + coin_bal_lock, 4)
                    pricebuff = priceupdate.PriceBuffer(market,
                                                        save_log_flag=False)
                    max_num = 5
                    run_time = 0
                    priceitem = None
                    # 循环取价格,防止中间出现取价格异常
                    while (run_time < max_num and priceitem is None):
                        priceitem = pricebuff.getpriceitem(
                            market, coin + '_btc')
                        run_time = run_time + 1

                    if priceitem is None:
                        print('coin:{0} has error to get price'.format(coin))
                        continue
                    currprice = priceitem.sell_price
                    coin_total_est_cny = round(coin_total_bal * currprice, 4)
                    # 根据自己的记录得到的balance和直接查询 得到的最终lock balance可能有差异,如果lock<open order balance则是有问题的,需要查询
                    coin_open_bal = self.get_open_bal(coin).get(
                        'total_units', 0)
                    # open订单的买入价格
                    coin_open_buy_amt = self.get_open_bal(coin).get(
                        'total_amount', 0)
                    # open订单的评估价格
                    coin_est_cny_open = round(
                        self.get_open_bal(coin).get('total_units', 0) *
                        currprice, 4)
                    # 检查OPEN order的UNIT和实际LOCK的UNIT是不是一致
                    if coin_bal_lock != coin_open_bal:
                        print(
                            'coin:{2},open bal:{0} is different from lock bal:{1})'
                            .format(coin_open_bal, coin_bal_lock, coin))
                    # 实际价格评估的资产
                    coin_est_cny_all = round(coin_total_bal * currprice, 4)
                    # open订单按实际买入的价格来计划金额,这个金额在每日比较会比较有用,排除价格变动造成的影响
                    coin_est_without_open = round(
                        (coin_total_bal - coin_open_bal) * currprice, 4)
                    # 总的金额,正在OPEN的卖单按买入价格计算
                    coin_est_cny_ori = coin_est_without_open + coin_open_buy_amt
                    # final result
                    coin_bal_item = {
                        'date': currdate,
                        'coin': coin,
                        'coin_est_cny_all': coin_est_cny_all,
                        'coin_est_cny_ori': coin_est_cny_ori,
                        'coin_total_bal': coin_total_bal,
                        'coin_open_bal': coin_open_bal,
                        'coin_bal_locked': coin_bal_lock,
                        'coin_open_buy_amt': coin_open_buy_amt,
                        'coin_est_cny_open': coin_est_cny_open,
                    }
                    coin_bal_item_str = json.dumps(coin_bal_item,
                                                   sort_keys=True)
                    open_bal_list.append(coin_bal_item_str)
                    # ----------各个COIN总的计算金额--------------------
                    # 所有COIN的总的估算金额
                    total_est_cny = round(total_est_cny + coin_est_cny_all, 4)
                    # 所有的估算金额,OPEN订单按买入金额计算
                    total_est_cny_ori = round(
                        total_est_cny_ori + coin_est_cny_ori, 4)
                    # open的总共买入金额
                    total_open_buy_amt = round(
                        total_open_buy_amt + coin_open_buy_amt, 4)
                    # open的总估算金额
                    total_open_est_cny = round(
                        total_open_est_cny + coin_est_cny_open, 4)

        # 所有COIN的结果
        total_bal = {
            'date': currdate,
            'total_est_cny': total_est_cny,
            'total_est_cny_ori': total_est_cny_ori,
            'total_cny_bal': total_cny_bal,
            'total_open_buy_amt': total_open_buy_amt,
            'total_cny_with_open': round(total_cny_bal + total_open_buy_amt,
                                         4),
            'total_open_est_cny': total_open_est_cny
        }
        total_bal_str = json.dumps(total_bal, sort_keys=True)
        # 保存数据到文件
        # save summary data
        fsumary = open('daillySummary.txt', 'a')
        fsumary.write(total_bal_str + '\n')
        fsumary.close()
        # save detail
        fdetail = open('daillyDetail.txt', 'a')
        for openitem in open_bal_list:
            fdetail.write(openitem + '\n')
        fdetail.close()
        # print(total_bal)
        return total_bal
Ejemplo n.º 14
0
    def coin_trans(self, market, trans_type, trans_price, price_item):
        coin = price_item.coin
        coin_pair = coin+'_btc'

        # 判断是不是满足交易的条件,不满足则退出不进行交易
        if trans_type == const.TRANS_TYPE_BUY:
            if self.check_trans_indi(coin) is False:
                print('{0}:不符合买入条件,可能是超过买入数量上限或者比例上限'.format(coin))
                return False

        # 对价格和交易单位进行rounding,否则有可能造成调用接口失败
        rounding_price = publicparameters.rounding_price(coin)
        rounding_unit = publicparameters.rounding_unit(coin)
        # 买入时的价格
        buy_price = price_item.buy_price
        # 交易UNITS
        trans_units = round(self.__trans_amount_per_trans / buy_price, rounding_unit)
        # 第一次交易卖出时的UNIT和买入UNIT会有一个0.5%的误差
        newtrans_units = trans_units
        # 对交易价格进行ROUNDING处理
        trans_price_rounding = round(trans_price, rounding_price)
        # 有些价格较贵,金额太小出现UNIT为0的情况,不需要再提交订单
        if trans_units < 0.00001:
            return False
        # 当前交易的对象
        if trans_type == const.TRANS_TYPE_BUY:
            orderitem = OrderItem(market, coin)
        elif trans_type == const.TRANS_TYPE_SELL:
            # 卖出时查找已经存在的priceitem,并更新相应的状态
            orderitem = self.get_order_item(price_item)
            if orderitem is None:
                return False
            else:
                trans_units = round(orderitem.buy_units, rounding_unit)
            # 卖出订单时检查买入订单的状态,如果没有买入成功则停止卖出,返回失败
            if orderitem.buy_status != const.ORDER_STATUS_CLOSED:
                # print('买入订单还没有成交,卖出取消!')
                return False
        # 交易的order_market
        order_market = self.order_market

        # 提交订单
        if trans_type == const.TRANS_TYPE_SELL:
            bal = order_market.getMyBalance(coin)
            # 可能出现余额不足的情况
            if bal > trans_units:
                trans_order = order_market.submitOrder(coin_pair, trans_type, trans_price_rounding, trans_units)
            # 处理第一次买入出现扣除手续费后卖出时余额不足的情况
            elif trans_units*0.99<bal:
                newtrans_units = round(trans_units*0.99,rounding_unit)
                trans_order = order_market.submitOrder(coin_pair, trans_type, trans_price_rounding, newtrans_units)
            # 余额不足的取消卖出交易
            else:
                orderitem.sell_status = const.ORDER_STATUS_CANCEL
                ormmysql.updateorder(orderitem)
                ormmysql.delorder(orderitem)
                print('{0}:余额不足,已经取消订单'.format(coin))
                return False
        else:
            trans_order = order_market.submitOrder(coin_pair, trans_type, trans_price_rounding, trans_units)
        #     trans_units)
        # # 取得返回订单的信息
        order_id = trans_order.order_id
        if order_id== -1111111:
            order_status = 'fail'
            return False
        else:
            order_status = order_market.getOrderStatus(order_id, coin)
            # 如果状态为None,说明取状态有异常,对于卖出默认为OPEN,防止出现多现卖出状态设置为None,继续卖出的情况
            if order_status is None:
                order_status = const.ORDER_STATUS_OPEN
        # 保留交易时的相关信息到orderitem对象中
        if trans_type == const.TRANS_TYPE_BUY:
            orderitem.buy_order_id = order_id
            orderitem.buy_status = order_status
            orderitem.buy_price = trans_price_rounding
            orderitem.buy_amount = self.__trans_amount_per_trans
            orderitem.buy_units = trans_units
            orderitem.buy_date = common.get_curr_time_str()
            orderitem.priceitem = price_item
            # 买入时新增加一个订单,卖出时则直接更新已经存在的订单
            # 保存数据到DB
            ormmysql.saveorder(orderitem)
            print('{0}:开始[{1}]交易,交易状态:{2}:PriceDate:{3},Coin:{4}, BuyPrice:{5}'.format(common.get_curr_time_str(), trans_type, order_status,
                                                               price_item.pricedate, price_item.coin,
                                                               price_item.buy_price))
        elif trans_type == const.TRANS_TYPE_SELL:
            orderitem.sell_order_id = order_id
            orderitem.sell_status = order_status
            orderitem.sell_price = trans_price_rounding
            orderitem.sell_amount = round(trans_units * trans_price_rounding, 10)
            orderitem.sell_units = trans_units
            orderitem.sell_date = common.get_curr_time_str()
            print('{0}:开始[{1}]交易,交易状态:{2}:PriceDate:{3},Coin:{4}, BuyPrice:{5}, SellPrice:{6}, ProfiteRate:{7}'.format(common.get_curr_time_str(), trans_type, order_status,
                                                               price_item.pricedate, price_item.coin,
                                                               price_item.buy_price, orderitem.sell_price, publicparameters.SELL_PROFIT_RATE))
            # 更新到DB
            ormmysql.updateorder(orderitem)
            # remove to log table if sell status is closed
            if order_status == const.ORDER_STATUS_CLOSED:
                ormmysql.delorder(orderitem)

        return True
        pass