Ejemplo n.º 1
0
 def __trans_apply(self):
     trans_success = False
     buy_cny = self.__price_base.sell_cny
     sell_cny = self.__price_vs.buy_cny
     rounding_num = self.get_rounding_num(self.__trans_coin_code)
     trans_units = round(self.__std_amount / buy_cny, rounding_num)
     self.__order_base = ordermanage.OrderManage(self.__market_base)
     self.__order_vs = ordermanage.OrderManage(self.__market_vs)
     # 调用买入操作
     buy_success = self.twin_trans(self.__order_base, 'buy',
                                   self.__trans_coin_code, trans_units,
                                   buy_cny)
     if buy_success:
         sell_success = self.twin_trans(self.__order_vs, 'sell',
                                        self.__trans_coin_code, trans_units,
                                        sell_cny)
         #目前的方案只要买入成功,则卖出订单不取消,只是检查状态当时有没有成交
         self.__trans_log()
         if sell_success:
             trans_success = True
         else:
             # 买入成功但是卖出失败的次数不能超过一定的数量,防止由于程序错误过度买入,消耗完全部的CNY,2017.7.7号发生过一次
             self.__sell_fail_times = self.__sell_fail_times + 1
         # 检查帐户的仓位并调整相应的盈利比例,使得下一次交易按新的盈利比例处理
         self.__update_profit_rate((self.__order_vs))
     return trans_success
Ejemplo n.º 2
0
 def __check_coin_pool(self,market_base,market_vs,coin_code):
     try:
         order_base= ordermanage.OrderManage(market_base)
         order_vs=ordermanage.OrderManage(market_vs)
         #返回标志
         result_flag=False
         #只检查两个市场的RMB金额,默认coin是足够交易的
         bal_base=float(order_base.getMyBalance('cny'))
         bal_vs=float(order_vs.getMyBalance('cny'))
         #检查coin的数量是不是满足当前市场是总市场容量的一半
         bal_coin_base=float(order_base.getMyBalance(coin_code))
         bal_coin_vs=float(order_vs.getMyBalance(coin_code))
         #大概的交易价格
         # vs的市场价格
         price_vs = pricemanage.PriceManage(market_vs, coin_code).get_coin_price()
         #币种 的阀值倍数
         coiin_bal_times=5
         #每次交易的单位数
         trans_unit_per_time=self.__std_amount/price_vs.buy_cny
         money_pool_amt=float(self.__std_amount*self.__money_pool_size)
         total_coin_bal=(bal_coin_base+bal_coin_vs)
         #资金量在3成以上才进行同步
         if float(bal_base/(bal_base+bal_vs))>0.3 or float(bal_base)>float(money_pool_amt*0.8):
             # 帐户低于总数的30%时进行均衡,只有总的币数大于每次交易的10倍 以上才进行均衡
             if bal_coin_base/total_coin_bal<0.3 and total_coin_bal>trans_unit_per_time*10:
                 result_flag=True
     except Exception as e:
         print(str(e))
         print('获取资金池状态是否需要均衡时出错')
     return result_flag
     pass
Ejemplo n.º 3
0
 def single_balance_market(self,market_base,market_vs,coin_code,money_pool_bal_indi=None):
     #如果需要均衡时则循环进行帐户均衡
     need_balance_flag=True
     single_bal_status=False
     order_base= ordermanage.OrderManage(market_base)
     order_vs=ordermanage.OrderManage(market_vs)
     self.__order_base=order_base
     self.__order_vs=order_vs
     # 检查两个市场的帐户状态
     try:
         status_comment='fail'
         #检查帐户状态,是不是需要均衡市场
         if money_pool_bal_indi:
             need_balance_flag = self.__check_money_pool(market_base, market_vs, coin_code)
         else:
             need_balance_flag = self.__check_coin_pool(market_base, market_vs, coin_code)
         exch_open_order_num=self.check_open_order_num(coin_code+'_cny')
         #买和卖方均衡ORDER的总数量不能超过X个,超过X个则等成交后再来生成
         if need_balance_flag and exch_open_order_num<=self.__max_open_num:
             single_bal_status=self.exch_balance(market_base,market_vs,coin_code)
             if single_bal_status:
                 status_comment = 'success'
             else:
                 status_comment = 'fail'
             #logging.info('%s: 已经自动对@%s增加RMB,对%s减少RMB进行了操作,状态:%s!' \
             #             % (self.__get_curr_time(), market_vs, market_base, status_comment))
                 #同步一次失败后10分钟后再进行同步,以确定这个交易能完成,如果完不成同步也确保不会有频繁的多次同步
                 #time.sleep(10*30)
         return status_comment
     except:
         pass
         return 'fail'
Ejemplo n.º 4
0
 def __check_money_pool(self,market_base,market_vs,coin_code):
     try:
         order_base= ordermanage.OrderManage(market_base)
         order_vs=ordermanage.OrderManage(market_vs)
         #返回标志
         result_flag=False
         #只检查两个市场的RMB金额,默认coin是足够交易的
         bal_base=order_base.getMyBalance('cny')
         bal_vs=order_vs.getMyBalance('cny')
         #检查coin的数量是不是满足当前市场是总市场容量的一半
         #bal_coin_base=float(order_base.getMyBalance(coin_code))
         bal_coin_vs=float(order_vs.getMyBalance(coin_code))
         #大概的交易价格
         # vs的市场价格
         price_vs = pricemanage.PriceManage(market_vs, coin_code).get_coin_price()
         #币种 的阀值倍数
         coiin_bal_times=5
         #每次交易的单位数
         trans_unit_per_time=self.__std_amount/price_vs.buy_cny
         money_pool_amt=self.__std_amount*self.__money_pool_size
         #帐户标准交易额的X倍,如果低于这个金额则进行两个市场的平衡
         if bal_vs<money_pool_amt:
             #只有待均衡的COIN的金额在资金池的3成以上才进行均衡
             if bal_coin_vs*price_vs.buy_cny/money_pool_amt>0.3:
                 result_flag=True
     except Exception as e:
         print(str(e))
         print('获取资金池状态是否需要均衡时出错')
     return result_flag
     pass
Ejemplo n.º 5
0
    def start(self):
        # 当前均衡的次数,即使是失败也计算在内
        bal_times = 0
        while(True):
            # 循环处理市场
            for market_base in self.__market_list:
                market_vs_list=list(self.__market_list)
                #移除作为base 的市场
                market_vs_list.remove(market_base)
                #对比每一个其它的市场
                for market_vs in market_vs_list:
                    #对每个coin进行分析
                    for coin in self.__coin_list:
                        #当前处理的市场
                        self.__market_base=market_base
                        self.__market_vs=market_vs
                        self.__order_base = ordermanage.OrderManage(self.__market_base)
                        self.__order_vs = ordermanage.OrderManage(self.__market_vs)
                        #开始处理帐户对倒,
                        if coin in self.__money_pool_coin:
                            #对资金池进行均衡
                            exch_status = self.single_balance_market(market_base, market_vs, coin,'Y')
                        else:
                            #对COIN进行均衡
                            exch_status = self.single_balance_market(market_base,market_vs,coin)
                        bal_times=bal_times+1
                        #time.sleep(10)
                        if bal_times%10==0:
                            print('%s: 执行了%d次均衡同步' % (self.__get_curr_time(), bal_times))

        pass
Ejemplo n.º 6
0
    def test_check_exch_bal_status(self):
        order_base= ordermanage.OrderManage('bter')
        order_vs=ordermanage.OrderManage('btc38')
        self.__order_base=order_base
        self.__order_vs=order_vs

        open_num=self.check_open_order_num('doge_cny')
        print('当前市场的均衡保单数量为:%d'%open_num)
Ejemplo n.º 7
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.º 8
0
 def getpriceitem(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)
     except Exception as e:
         # print('取得[{1}]价格列表时错误:{0}'.format(str(e), coin_pair))
         return None
     return priceitem
Ejemplo n.º 9
0
 def __init__(self, market):
     self.__market = market
     # 定期投资的相关参数
     # self.__regular_param = config.regular_invest_param
     # self.__regular_param2 = config.regular_invest_param2
     # 每次买入的金额
     # self.__trans_amount_per_trans = self.__regular_param.get('buy_amt')
     # 每次买入的时间
     # self.__buy_time = self.__regular_param.get('buy_time')
     # 买入的频率,以小时为单位
     # self.__buy_freq = self.__regular_param.get('buy_freq')
     # 一个COIN的总共投资上限
     # self.__buy_max_amt = self.__regular_param.get('buy_max_amt')
     # 止盈比例
     # self.__sell_profit_rate = self.__regular_param.get('sell_profit_rate')
     # 止损比例
     # self.__stop_lost_rate = self.__regular_param.get('stop_lost_rate')
     # 操作的coin list
     # self.__coin_list = self.__regular_param.get('coin_list').split(',')
     self.__coin_list = self.get_coinfig_coinlist()
     # 订单状态
     const.ORDER_STATUS_OPEN = 'open'
     const.ORDER_STATUS_CLOSED = 'closed'
     const.ORDER_STATUS_CANCEL = 'cancelled'
     const.TRANS_TYPE_BUY = 'buy'
     const.TRANS_TYPE_SELL = 'sell'
     # 取消订单状态
     const.CANCEL_STATUS_SUCC = 'success'
     const.CANCEL_STATUS_FAIL = 'fail'
     # 市场的交易处理器
     self.order_market = ordermanage.OrderManage(market)
Ejemplo n.º 10
0
    def __check_balance_flag(self,market_base, market_vs,coin_code):
        order_base= ordermanage.OrderManage(market_base)
        order_vs=ordermanage.OrderManage(market_vs)
        #只检查两个市场的RMB金额,默认coin是足够交易的
        bal_base=order_base.getMyBalance('cny')
        bal_vs=order_vs.getMyBalance('cny')

        #检查coin的数量是不是满足当前市场是总市场容量的一半
        bal_coin_base=float(order_base.getMyBalance(coin_code))
        bal_coin_vs=float(order_vs.getMyBalance(coin_code))
        total_coin_bal=bal_coin_base+bal_coin_vs

        #大概的交易价格
        # base的市场价格
        price_base = pricemanage.PriceManage(market_base, coin_code).get_coin_price()
        # 需要对比的市场价格
        #price_vs = pricemanage.PriceManage(market_vs, coin_code).get_coin_price()


        need_exchange=False
        #均衡市场是标准交易的多少倍
        bal_times=100
        #币种 的阀值倍数
        coiin_bal_times=5
        #每次交易的单位数
        trans_unit_per_time=self.__std_amount/price_base.sell_cny
        #帐户标准交易额的100倍,如果低于这个金额则进行两个市场的平衡
        if bal_vs<float(self.__std_amount*bal_times):
            #需要卖出市场的COIN的比例是不是占总COIN的X成以上并且余额是交易单位的指定倍数以上
            if float(bal_coin_vs)>float(total_coin_bal*0.3):
                # Coin is enough and need sell coin to get money, the estimated amount is greater than 1000
                if float(bal_coin_vs)>float(total_coin_bal*0.3) and (price_base.sell_cny*bal_coin_vs)>1000:
                    need_exchange=True
                else:
                    need_exchange=False
            else:
                # 对于COIN来说,只要是小于总量的30%才需要进行均衡
                if bal_coin_vs<float(trans_unit_per_time*coiin_bal_times) and bal_coin_vs<float(total_coin_bal*0.3):
                    need_exchange=True
        else:
            # 对于COIN来说,只要是小于总量的30%才需要进行均衡
            if bal_coin_vs < float(trans_unit_per_time * coiin_bal_times) and bal_coin_vs < float(total_coin_bal * 0.3):
                need_exchange = True
            else:
                need_exchange=False
        return need_exchange
Ejemplo n.º 11
0
    def __coin_rearch(self):
        # 比较多个市场之间的价格
        for market_base in self.__market_list:
            market_vs_list = list(self.__market_list)
            # 移除作为base 的市场
            market_vs_list.remove(market_base)
            # 对比每一个其它的市场
            for market_vs in market_vs_list:
                # 对每个coin进行分析
                for coin in self.__coin_list:
                    # base的市场价格
                    price_base = pricemanage.PriceManage(
                        market_base, coin).get_coin_price()
                    # 需要对比的市场价格
                    price_vs = pricemanage.PriceManage(market_vs,
                                                       coin).get_coin_price()

                    price_check_result = self.__price_check(
                        coin, price_base, price_vs)
                    # 如果价格可以进行买卖刚返回
                    if price_check_result:
                        # 对于达到要求的保存到类变量中,交易函数进行处理
                        self.__market_base = market_base
                        self.__market_vs = market_vs
                        self.__price_base = price_base
                        self.__price_vs = price_vs
                        # 满足交易的coin code
                        self.__trans_coin_code = coin
                        # 把交易实例保存起来
                        # Base account的交易实例
                        self.__order_base = ordermanage.OrderManage(
                            self.__market_base)
                        # VS市场
                        self.__order_vs = ordermanage.OrderManage(
                            self.__market_vs)

                        # 预期盈利金额
                        profitamt = (self.__std_amount / price_base.sell_cny
                                     ) * (price_vs.buy_cny -
                                          price_base.sell_cny)
                        currtime = time.strftime('%Y-%m-%d %H:%M:%S',
                                                 time.localtime(time.time()))
                        print('Date:%s,Coin:%s,BaseMarket(Buy):%s, VSmarket(Sell):%s,Buy price:%f,Sell price:%f,投资%f预期盈利:%f' \
                              % (currtime,coin, market_base, market_vs, price_base.sell_cny, price_vs.buy_cny, self.__std_amount,
                                 profitamt))
Ejemplo n.º 12
0
    def exch_balance(self,market_base, market_vs, coin_code):
        order_base = ordermanage.OrderManage(market_base)
        order_vs = ordermanage.OrderManage(market_vs)
        # base的市场价格
        price_base = pricemanage.PriceManage(market_base, coin_code).get_coin_price()
        # 需要对比的市场价格
        price_vs = pricemanage.PriceManage(market_vs, coin_code).get_coin_price()
        #trans_price = float(self.__get_trans_price(price_base, price_vs, coin_code))

        match_price_flag=self.__price_check(coin_code,price_base,price_vs)
        #在约定的范围价格变动范围之内
        if match_price_flag:
            trans_price_buy=price_base.sell_cny
            trans_price_sell=price_vs.buy_cny
        else:
            return False
        #TODO test purpose
        #trans_price=0.01598
        # 价格两个市场变动范围不在约定的范围 内则不返回价格,不需要进行交易
        #if trans_price == None:
        #    return False
        trans_amount=self.__std_amount*self.__exch_times
        # 交易的单位是每次交易的X倍,
        # 要非常 小心 这里面的小数位,需要BTC38的接口小数位数太长会报错,接口太SB了, 不知道自己处理一下
        robot=traderobot.TradeRobot()
        trans_units = round(float(self.__std_amount / trans_price_buy * self.__exch_times),robot.get_rounding_num(coin_code))

        tradeapi=robot
        trans_status=False
        # 调用买入操作
        buy_success = tradeapi.twin_trans(order_base, 'buy', coin_code, trans_units, trans_price_buy)
        if buy_success:
            sell_success = tradeapi.twin_trans(order_vs, 'sell', coin_code, trans_units, trans_price_sell)
            # 目前的方案只要买入成功,则卖出订单不取消,只是检查状态当时有没有成交
            if sell_success:
                trans_status = True
                print('%s:均衡交易:成功,已经成功卖出:%s@%s,金额:%f,从市场@%s同样买入:当前成交!' \
                             % (self.__get_curr_time(), coin_code, market_vs, trans_amount, market_base))
                logging.info('%s:均衡交易:成功,已经成功卖出:%s@%s,金额:%f,从市场@%s同样买入:当前成交!' \
                             % (self.__get_curr_time(), coin_code, market_vs, trans_amount, market_base))
            else:
                logging.warning('%s:均衡交易:在途,已经成功卖出:%s@%s,金额:%f,从市场@%s同样买入:当前未成交!' \
                             % (self.__get_curr_time(), coin_code, market_vs, trans_amount, market_base))
        return trans_status
        pass
Ejemplo n.º 13
0
    def test_twin_trans_sell_overtime(self):

        self.__order_base = ordermanage.OrderManage('bter')
        order_market = self.__order_base
        sell_order = order_market.submitOrder('doge_cny', 'sell', 0.03, 150)
        sell_order_id = sell_order.order_id
        resell_status = self.__twin_trans_sell_overtime_process(
            order_market, sell_order_id, 'doge', 0.01735, 100)
        pass
Ejemplo n.º 14
0
 def test_twin_trans(self):
     # VS市场
     #测试卖出操作
     test_market = 'bter'
     self.__order_vs = ordermanage.OrderManage(test_market)
     self.__order_base = ordermanage.OrderManage(test_market)
     status_bter = False
     status_bter = self.twin_trans(self.__order_base, 'buy', 'doge', 100,
                                   0.05)
     print('test trans(SELL) exec result @%s:' % test_market)
     if status_bter:
         print('transaction done successfully!')
     else:
         print('transaction failed!')
     test_market = 'btc38'
     """
     self.__order_vs = ordermanage.OrderManage(test_market)
     status_btc38 = self.twin_trans(self.__order_vs,'sell', 'doge', 1000, 0.05)
     print('test trans(SELL) exec result @%s:' % test_market)
     if status_btc38:
         print('transaction done successfully!')
     else:
         print('transaction failed!')
     """
     #测试买入操作
     test_market = 'bter'
     self.__order_base = ordermanage.OrderManage(test_market)
     status_bter = self.twin_trans(self.__order_base, 'buy', 'doge', 200,
                                   0.012)
     print('test trans(BUY) exec result @%s:' % test_market)
     if status_bter:
         print('transaction done successfully!')
     else:
         print('transaction failed!')
     test_market = 'btc38'
     self.__order_base = ordermanage.OrderManage(test_market)
     status_btc38 = self.twin_trans(self.__order_base, 'buy', 'doge', 200,
                                    0.012)
     print('test trans(BUY) exec result @%s:' % test_market)
     if status_btc38:
         print('transaction done successfully!')
     else:
         print('transaction failed!')
Ejemplo n.º 15
0
    def __init__(self, market):
        # 订单状态
        const.ORDER_STATUS_OPEN = 'open'
        const.ORDER_STATUS_CLOSED = 'closed'
        const.ORDER_STATUS_CANCEL = 'cancelled'
        const.TRANS_TYPE_BUY='buy'
        const.TRANS_TYPE_SELL='sell'
        # 取消订单状态
        const.CANCEL_STATUS_SUCC = 'success'
        const.CANCEL_STATUS_FAIL= 'fail'


        # 最大的交易订单数,
        self.__max_open_order_pool = publicparameters.MAX_OPEN_ORDER_POOL
        # 每次交易的金额
        self.__trans_amount_per_trans = publicparameters.TRANS_AMOUNT_PER_ORDER
        # 止盈比例
        self.__sell_profit_rate = publicparameters.SELL_PROFIT_RATE
        # 市场的交易处理器
        self.order_market = ordermanage.OrderManage(market)
        # 市场
        self.market = market

        pass
Ejemplo n.º 16
0
 def __init__(self, market):
     self.__market = market
     #交易市场,用来执行查询及提交订单的处理
     self.__order_market = ordermanage.OrderManage(market)
     #市场研究的coin list
     self.__coin_list = ['ltc', 'doge', 'btc']
Ejemplo n.º 17
0
 def get_balance(self):
     for market in self.__market_list:
         order_market = ordermanage.OrderManage(market)
         market_bal = order_market.getMyBalance()
Ejemplo n.º 18
0
    def output_summary(self, filename):
        file = open(filename, 'a')
        #每个市场的明细
        file_detail = open(
            filename.split('.')[0] + '_detail.' + filename.split('.')[1], 'a')
        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_output = {}
        all_coin_bal = {}

        # 按币种循环生成各个市场的帐户的情况
        for coin in all_coin_list:
            all_coin_bal[coin] = []
            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']
                    coin_total_bal = round(coin_bal + coin_bal_lock, 4)
                    all_coin_bal[coin].append({
                        'market': market,
                        'available': coin_total_bal
                    })
                else:
                    all_coin_bal[coin].append({
                        'market': market,
                        'available': 0
                    })
        # 按币种输出
        all_coin_list.sort()
        for coin in all_coin_list:
            need_output = False
            all_market_values = 0
            coin_value = all_coin_bal[coin]
            for item in coin_value:
                if float(item['available']) > 0:
                    need_output = True
                #市场之间的总和,针对同一币种
                all_market_values = round(
                    all_market_values + item['available'], 4)
                pass
            if need_output:
                coin_value = all_coin_bal[coin]
                for item in coin_value:
                    coin_bal = str(round(item['available'], 4))
                    market = item['market']
                    all_output[market] = all_output.get(
                        market,
                        '') + '%s|%s|' % (coin.ljust(6), coin_bal.rjust(12))
                all_output['ALL'] = all_output.get('ALL', '') + '%s|%s|' % (
                    coin.ljust(6), str(all_market_values).rjust(12))

        # 输出每个市场的余额
        currtime = common.CommonFunction.get_curr_time()
        for market in self.__market_list:
            output = '%s|%s|%s|\n' % (currtime, market.ljust(6),
                                      all_output[market])
            file_detail.write(output)
        summary_output = '%s|%s|%s|\n' % (currtime, 'ALL'.ljust(6),
                                          all_output['ALL'])
        file.write(summary_output)
        file.close()
        file_detail.close()
Ejemplo n.º 19
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.º 20
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Owen_Study/[email protected]'
# Create date: 17-8-5 上午11:50

import ordermanage, ormmysql
'''注释'''

if __name__ == '__main__':
    order_market = ordermanage.OrderManage('btc38')

    open_order_list_web = order_market.getOpenOrderList('zcc')
    open_order_list_db = ormmysql.allopenorderlist()
    for openorder in open_order_list_web:
        coin = openorder.coin_code_pair
        order_id_web = int(openorder.order_id)
        order_units_web = float(openorder.trans_unit)
        for dbopenorder in open_order_list_db:
            order_id_db = dbopenorder.sell_order_id
            order_units_db = dbopenorder.sell_units
            if order_id_web == order_id_db:
                if order_units_web == order_units_db:
                    break
                else:
                    print(
                        '{0}, order_id:{1}, order_unts_web:{2}, order_units_db{3}'
                        .format(coin, order_id_db, order_units_web,
                                order_units_db))
                    break
        else:
Ejemplo n.º 21
0
    def exch_balanceX(self,market_base, market_vs, coin_code):
        order_base= ordermanage.OrderManage(market_base)
        order_vs=ordermanage.OrderManage(market_vs)
        # base的市场价格
        price_base = pricemanage.PriceManage(market_base, coin_code).get_coin_price()
        # 需要对比的市场价格
        price_vs = pricemanage.PriceManage(market_vs, coin_code).get_coin_price()

        trans_price=self.__get_trans_price(price_base,price_vs,coin_code)
        #价格两个市场变动范围不在约定的范围 内则不返回价格,不需要进行交易
        if trans_price==None:
            return False
        sell_status=None
        buy_status=None
        #交易的单位是每次交易的X倍, TODO test
        trans_units=self.__std_amount/trans_price*self.__exch_times
        #同步交易,先卖后买
        sell_trans=order_vs.submitOrder(coin_code+'_cny','sell',trans_price,trans_units)
        sell_order_id=sell_trans.order_id
        if sell_order_id==1111111:
            sell_status='closed'
        #买入交易
        #buy_trans=order_base.submitOrder(coin_code+'_cny','buy',trans_price,trans_units)
        #buy_order_id=buy_trans.order_id
        #if buy_order_id == 1111111:
        #    buy_status = 'closed'
        #循环检查状态,直至交易成功后才结束返回
        trans_status=False
        waiting_seconds=0
        #最多待时间,持续检查均衡订单的状态
        max_waiting_seconds=5
        #按每次交易金额的X倍来进行帐户之间平衡
        trans_amount=self.__std_amount*self.__exch_times
        while(not trans_status and waiting_seconds<max_waiting_seconds):
            try:
                if sell_status!='closed':
                    sell_status = order_vs.getOrderStatus(sell_order_id, coin_code)
                else:
                    # 成功后再开始买入操作
                    if buy_status==None:
                        buy_trans = order_base.submitOrder(coin_code + '_cny', 'buy', trans_price, trans_units)
                        buy_order_id = buy_trans.order_id
                        time.sleep(0.1)
                        if sell_order_id == 1111111:
                            sell_status = 'closed'
                        else:
                            buy_status = order_base.getOrderStatus(buy_order_id, coin_code)
                    elif buy_status!='closed':
                        buy_status = order_base.getOrderStatus(buy_order_id, coin_code)
            except Exception as e:
                print(str(e))
                pass
            finally:
                time.sleep(1)
                waiting_seconds = waiting_seconds + 1
                if sell_status=='closed' and buy_status=='closed':
                    logging.info('%s:均衡交易:成功,已经成功卖出:%s@%s,金额:%f,从市场@%s同样买入:当前成交!'\
                    %(self.__get_curr_time(),coin_code,market_vs,trans_amount,market_base))
                    trans_status=True
                    waiting_seconds=max_waiting_seconds+5

        if waiting_seconds== max_waiting_seconds:
            #卖出一直未成功,则取消本次的操作
            if sell_status!='closed' and buy_status==None:
                cancel_status=order_base.cancelOrder(sell_order_id,coin_code)
                if cancel_status=='fail':
                    logging.warning('%s:取消卖单状态:失败,均衡交易中卖出%s@%s,金额:%f在指定时间未内成交!'%(self.__get_curr_time(),coin_code),market_vs,trans_amount)
                else:
                    logging.info('%s:取消卖单状态:成功,均衡交易中卖出%s@%s,金额:%f在指定时间未内成交!' % (self.__get_curr_time(), coin_code),
                                 market_vs, trans_amount)
            else:
                logging.warning('%s:均衡交易(buyOrderId:%s):在途,已经成功卖出:%s@%s,金额:%f,从市场@%s同样买入:当前未成交!' \
                             % (self.__get_curr_time(),buy_order_id, coin_code, market_vs, trans_amount, market_base))

        return trans_status
        pass
Ejemplo n.º 22
0
 def test_check_account(self):
     self.__order_base = ordermanage.OrderManage('bter')
     self.__order_vs = ordermanage.OrderManage('btc38')
     self.__trans_coin_code = 'ppc'
Ejemplo n.º 23
0
    def price_analyze(self):
        #比较多个市场之间的价格
        for market_base in self.__market_list:
            market_vs_list = list(self.__market_list)
            #移除作为base 的市场
            market_vs_list.remove(market_base)
            #对比每一个其它的市场
            for market_vs in market_vs_list:
                #对每个coin进行分析
                for coin in self.__coin_list:
                    #base的市场价格
                    #print('%s:is requesting price@%s' % (self.__get_curr_time(),market_base))
                    price_base = pricemanage.PriceManage(
                        market_base, coin).get_coin_price()
                    #需要对比的市场价格
                    #print('%s:is requesting price@%s' % (self.__get_curr_time(),market_vs))
                    price_vs = pricemanage.PriceManage(market_vs,
                                                       coin).get_coin_price()
                    # print('%s:is comparing price'%self.__get_curr_time())
                    price_check_result = self.__price_check(
                        coin, price_base, price_vs)

                    self.__check_price_num = self.__check_price_num + 1
                    if self.__check_price_num % 10 == 0:
                        print('%s: 已经检查了%d次的价格' %
                              (self.__get_curr_time(), self.__check_price_num))

                    # TODO for testing
                    #price_check_result=True
                    #如果价格可以进行买卖刚返回
                    if price_check_result:
                        #对于达到要求的保存到类变量中,交易函数进行处理
                        self.__market_base = market_base
                        self.__market_vs = market_vs
                        self.__price_base = price_base
                        self.__price_vs = price_vs
                        # 满足交易的coin code
                        self.__trans_coin_code = coin
                        #把交易实例保存起来
                        # Base account的交易实例
                        self.__order_base = ordermanage.OrderManage(
                            self.__market_base)
                        # VS市场
                        self.__order_vs = ordermanage.OrderManage(
                            self.__market_vs)

                        #预期盈利金额
                        profitamt = (self.__std_amount / price_base.sell_cny
                                     ) * (price_vs.buy_cny -
                                          price_base.sell_cny)

                        print('%s: Coin:%s,BaseMarket(Buy):%s, VSmarket(Sell):%s,Buy price:%f,Sell price:%f,投资%f预期盈利:%f'\
                              %(self.__get_curr_time(),coin,market_base,market_vs,price_base.sell_cny,price_vs.buy_cny,self.__std_amount,profitamt))
                        #开始处理交易
                        # 检查帐户的仓位并调整相应的盈利比例
                        #print('%s: is checking account balance'%self.__get_curr_time())
                        account_balance = self.__check_account()
                        # 如果过多的买入成功,卖出失败则停止进行自动交易,防止异常的一直出现买入的情况
                        if account_balance and self.__sell_fail_times < self.__max_sell_fail_times:
                            #检查帐户的仓位并调整相应的盈利比例
                            #print('%s: is doing transaction.'%self.__get_curr_time())
                            trans_status = self.__trans_apply()
                            if trans_status:
                                print('交易成功!')
                            else:
                                print('交易失败/或卖出当时未成功!')
                        else:
                            print('帐户余额不足!')