예제 #1
0
class Fteth():
    def __init__(self):
        # initialize the Fcoin API
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'fteth'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(), 6)]
        # don't quite know what are these
        self.eth_sxf = 0.0
        self.ft_sxf = 0.0
        self.begin_balance = self.get_balance()

    def digits(self, num, digit):
        '''
        Get rid of decimals after number of [num] digits
        '''
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        current_price = ticker['data']['ticker'][0]
        print('new trade price: ', current_price)
        return current_price

    def get_balance(self):
        dic_balance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_balance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_balance

    def process(self):
        price = self.digits(self.get_ticker(), 8)

        self.oldprice.append(price)
        self.dic_balance = self.get_balance()
        ft = self.dic_balance['ft']
        eth = self.dic_balance['eth']

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        if not order_list or len(order_list) < 2:
            # make sure we will make profit from this
            # check eth balance and current price
            if eth and abs(price / self.oldprice[len(self.oldprice) - 2] -
                           1) < 0.02:
                # if the price is above the average of 2 latest prices

                if price * 2 > self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    # calculate amount to buy
                    amount = self.digits(ft.available * 0.25, 2)

                    if amount > 5:
                        # but some FT
                        data = self.fcoin.buy(self.symbol, price, amount)
                        # if the trade is success
                        if data:
                            self.ft_sxf += amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                    else:
                        if float(ft.available) * 0.25 > 5:
                            # use 25 precentage
                            amount = self.digits()
                            data = self.fcoin.sell(self.symbol, price, amount)
                            if data:
                                # record transaction fee
                                self.eth_sxf += amount * price * 0.001
                                # record time
                                self.time_order = time.time()
                                #
                                self.order_id = data['data']
                                print('sell success')
                else:
                    print('error')
            else:
                print('system busy')
                if len(order_list) >= 1:
                    data = self.fcoin.cancel_order(order_list[len(order_list) -
                                                              1]['id'])
                    print(order_list[len(order_list) - 1])
                    if data:
                        if order_list[len(order_list) -
                                      1]['side'] == 'buy' and order_list[
                                          len(order_list) -
                                          1]['symbol'] == 'fteth':
                            self.ft_sxf -= float(
                                order_list[len(order_list) -
                                           1]['amount']) * 0.001
                        elif order_list[len(order_list) -
                                        1]['side'] == 'sell' and order_list[
                                            len(order_list) -
                                            1]['symbol'] == 'fteth':
                            self.eth_sxf -= float(
                                order_list[len(order_list) -
                                           1]['amount']) * float(
                                               order_list[len(order_list) -
                                                          1]['price']) * 0.001

    def loop(self):
        while True:
            try:
                self.process()
                print('success')
            except:
                print('err')
            time.sleep(5)
예제 #2
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        self.now_price = ticker['data']['ticker'][0]
        self.log.info("now price%s" % self.now_price)
        return self.now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def save_csv(self, array):
        with open("data/trade.csv", "a+", newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None

    def my_process(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        print("usdt ---", usdt.available, "ft----", ft.available)
        price = self.digits(self.get_ticker(), 6)
        new_old_price = abs(price / self.oldprice - 1) * 100
        print("new price --", price)
        print("old price --", self.oldprice)
        print("price波动百分比----", new_old_price)

        if 0.001 < new_old_price < 1:
            if price > self.oldprice and self.fall_rise < 6:
                self.fall_rise = self.fall_rise + 1
            elif price < self.oldprice and self.fall_rise > -6:
                self.fall_rise = self.fall_rise - 1
            print("跌涨标志----", self.fall_rise)

            order_list = self.fcoin.list_orders(symbol=self.symbol,
                                                states="submitted")["data"]
            print("size", len(order_list))
            if not order_list or len(order_list) < 3:
                self.count_flag = 0
                data = self.fcoin.get_market_depth("L20", self.symbol)
                bids_price = data["data"]["bids"][0]
                asks_price = data["data"]["asks"][0]
                dif_price = (asks_price * 0.001 + bids_price * 0.001) / 2
                if self.fall_rise > 3 or (price > self.oldprice
                                          and new_old_price > 0.4):
                    print("涨--------------")
                    bids_dif = bids_price - dif_price * 0.6
                    asks_dif = asks_price + dif_price * 1.5
                elif self.fall_rise < -3 or (price < self.oldprice
                                             and new_old_price > 0.4):
                    print("跌---------------")
                    bids_dif = bids_price - dif_price * 1.5
                    asks_dif = asks_price + dif_price * 0.6
                else:
                    print("平衡-------------")
                    bids_dif = bids_price - dif_price
                    asks_dif = asks_price + dif_price

                bids_price_b = self.digits(bids_dif, 6)
                print("bids_price", bids_price_b)
                asks_price_a = self.digits(asks_dif, 6)
                print("asks_price", asks_price_a)
                print("交易差------", (asks_price_a - bids_price_b) * 1000)

                asks_data = self.fcoin.sell(self.symbol, asks_price_a, 6)
                if asks_data:
                    print("sell success")
                bids_data = self.fcoin.buy(self.symbol, bids_price_b, 6)
                if bids_data:
                    print("buy success")
            else:
                self.count_flag = self.count_flag + 1
                time.sleep(2)
                print("sleep end")
                if len(order_list) >= 1:
                    self.log.info("cancel order {%s}" % order_list[-1])
                    print("****************cancel order ***********")
                    order_id = order_list[-1]['id']
                    self.count_flag = 0
                    data = self.fcoin.cancel_order(order_id)
                    self.log.info("cancel result {%s}" % data)
        else:
            print("##########当前波动无效###########")
        self.oldprice = price

    def process(self):
        price = self.digits(self.get_ticker(), 6)
        self.oldprice.append(price)
        self.dic_balance = self.get_blance()
        ft = self.dic_balance['ft']
        usdt = self.dic_balance['usdt']

        self.log.info("usdt has--[%s]   ft has--[%s]" %
                      (usdt.balance, ft.balance))

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']
        print(order_list)
        self.log.info("order trading: %s" % order_list)

        if not order_list or len(order_list) < 2:
            if usdt and abs(price / self.oldprice[len(self.oldprice) - 2] -
                            1) < 0.02:
                if price * 2 < self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            self.fee = amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                            self.type = 1
                            self.log.info(
                                'buy success price--[%s] amout--[%s] fee--[%s]'
                                % (price, amount, self.fee))
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.fee = amount * price * 0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            self.type = 2
                            self.log.info(
                                "sell success price--[%s] amout--[%s] fee--[%s]"
                                % (price, amount, self.fee))

            else:
                print('价格波动过大 %s' % usdt)
                self.log.info("价格波动过大%s" % usdt)
        else:
            print('system busy')
            if len(order_list) >= 1:
                self.log.info("cancel order {%s}" % order_list[-1])
                order_id = order_list[-1]['id']
                data = self.fcoin.cancel_order(order_id)
                self.log.info("cancel result {%s}" % data)
                if data:
                    if order_list[len(order_list) -
                                  1]['side'] == 'buy' and order_list[
                                      len(order_list) -
                                      1]['symbol'] == 'ftusdt':
                        self.fee = -float(
                            order_list[len(order_list) - 1]['amount']) * 0.001
                    elif order_list[len(order_list) -
                                    1]['side'] == 'sell' and order_list[
                                        len(order_list) -
                                        1]['symbol'] == 'ftusdt':
                        self.fee = -float(
                            order_list[len(order_list) - 1]['amount']) * float(
                                order_list[len(order_list) -
                                           1]['price']) * 0.001
                    self.type = 3
                    self.order_id = order_id

    def loop(self):
        while True:
            try:
                self.my_process()
                # time1 = time.time()
                # self.process()
                # array = [self.order_id,self.now_price,self.type,self.fee,self.symbol,time.strftime('%Y-%m-%d %H:%M:%S')]
                # if self.type != 0:
                #     self.save_csv(array)
                # self.log.info("--------success-------")
                # time2 = time.time()
                # self.log.info("app time--%s"% str(time2-time1))
                time.sleep(5)
            except Exception as e:
                self.log.info(e)
                print(e)
예제 #3
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        print(data)
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def process(self):
        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']

        usdt = self.dic_balance['usdt']
        print('usdt  has ....', usdt.available, 'ft has ...', ft.available)
        price = self.digits(self.get_ticker(), 6)

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        print('order list', order_list)
        if not order_list or len(order_list) < 3:
            if usdt and abs(price / self.oldprice - 1) < 0.02:
                if price > self.oldprice:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success', data)
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.time_order = time.time()
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')
        else:
            print('system busy')
            order_list = self.fcoin.list_orders(symbol=self.symbol,
                                                states='submitted')['data']
            if len(order_list) >= 1:
                self.fcoin.cancel_order(order_list[0]['id'])
        self.oldprice = price

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(1)
예제 #4
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.symbol = config.socket+config.blc
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.get_prices()
        self.socket_sxf=0.0
        self.blc_sxf=0.0
        self.begin_balance=self.get_blance()
        
    def get_prices(self):
        i=2
        prices=[]
        while i>0:
           prices.append(self.digits(self.get_ticker(),6))
           i-=1
           time.sleep(1)
        return prices

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance

    def process(self):
        price = self.digits(self.get_ticker(),6)
        
        self.oldprice.append(price)
        
        p1=self.oldprice[len(self.oldprice)-2]
        p2=self.oldprice[len(self.oldprice)-3]
        
        self.dic_balance = self.get_blance()

        socket = self.dic_balance[config.socket]

        blc = self.dic_balance[config.blc]  
        
        print(config.blc+'_now  has ....', blc.balance, config.socket+'_now has ...', socket.balance)
        print(config.blc+'_sxf  has ....', self.blc_sxf, config.socket+'_sxf has ...', self.socket_sxf)
        print(config.blc+'_begin  has ....', self.begin_balance[config.blc].balance, config.socket+'_begin has ...', self.begin_balance[config.socket].balance)
        print(config.blc+'_all_now  has ....', blc.balance+self.blc_sxf, config.socket+'_all_now has ...', socket.balance+self.socket_sxf)

        order_list = self.fcoin.list_orders(symbol=self.symbol,states='submitted')['data'] 

        if not order_list or len(order_list) < 2:
            if blc and abs(price/self.oldprice[len(self.oldprice)-2]-1)<0.02:
                if price*2>p1+p2:
                    amount = self.digits(blc.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success',data)
                            self.socket_sxf += amount*0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    if  float(socket.available) * 0.25 > 5:
                        amount = self.digits(socket.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.blc_sxf += amount*price*0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')
        else:
            print('system busy')
            if len(order_list) >= 1:
                data=self.fcoin.cancel_order(order_list[len(order_list)-1]['id'])
                print(order_list[len(order_list)-1])
                if data:
                    if order_list[len(order_list)-1]['side'] == 'buy' and order_list[len(order_list)-1]['symbol'] == self.symbol:
                        self.socket._sxf -= float(order_list[len(order_list)-1]['amount'])*0.001
                    elif order_list[len(order_list)-1]['side'] == 'sell' and order_list[len(order_list)-1]['symbol'] == self.symbol:
                        self.blc_sxf -= float(order_list[len(order_list)-1]['amount'])*float(order_list[len(order_list)-1]['price'])*0.001
        
        

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(5)
예제 #5
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(), 6)]
        self.usdt_sxf = 0.0
        self.ft_sxf = 0.0
        self.begin_balance = self.get_blance()

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def process(self):
        price = self.digits(self.get_ticker(), 6)

        self.oldprice.append(price)

        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']

        usdt = self.dic_balance['usdt']

        print('usdt_now  has ....', usdt.balance, 'ft_now has ...', ft.balance)
        print('usdt_sxf  has ....', self.usdt_sxf, 'ft_sxf has ...',
              self.ft_sxf)
        print('usdt_begin  has ....', self.begin_balance['usdt'].balance,
              'ft_begin has ...', self.begin_balance['ft'].balance)
        print('usdt_all_now  has ....', usdt.balance + self.usdt_sxf,
              'ft_all_now has ...', ft.balance + self.ft_sxf)

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        if not order_list or len(order_list) < 2:
            # make sure it is still profitable
            # if usdt balance is bigger than zero and
            # the current price is within 2% fluctuation compared to the latest old price
            if usdt and abs(price / self.oldprice[len(self.oldprice) - 2] -
                            1) < 0.02:
                # if the price is above the average of 2 latest prices
                if price * 2 > self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    # set the amount for buying using 25% of remaining usdt
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    # if amount is bigger than 5
                    if amount > 5:
                        # buy it
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success', data)
                            self.ft_sxf += amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    # if the price is not bigger than the average which means the price is dropping
                    if float(ft.available) * 0.25 > 5:
                        # sell 25 precent of fts we are holding
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            # record transaction fee
                            self.usdt_sxf += amount * price * 0.001
                            # record time
                            self.time_order = time.time()
                            #
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')

        else:
            print('system busy')
            if len(order_list) >= 1:
                data = self.fcoin.cancel_order(order_list[len(order_list) -
                                                          1]['id'])
                print(order_list[len(order_list) - 1])
                if data:
                    if order_list[len(order_list) -
                                  1]['side'] == 'buy' and order_list[
                                      len(order_list) -
                                      1]['symbol'] == 'ftusdt':
                        self.ft_sxf -= float(
                            order_list[len(order_list) - 1]['amount']) * 0.001
                    elif order_list[len(order_list) -
                                    1]['side'] == 'sell' and order_list[
                                        len(order_list) -
                                        1]['symbol'] == 'ftusdt':
                        self.usdt_sxf -= float(
                            order_list[len(order_list) - 1]['amount']) * float(
                                order_list[len(order_list) -
                                           1]['price']) * 0.001

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(5)
예제 #6
0
                    #     if i['currency']=='btc':BTC_amount = float(i['available'])
                    # sell_amount =  BTC_amount -0.00001
                    # if sell_amount> min_amount:
                #     result = fcoin.margin_sell(symbol, round(price_ask - ratio * price_increment, 1), round(min_amount, 4))
                #     sell_id.append(result['data'])
                #     logger.info('>> sell   ' + str(price_ask) + '   ' + str(min_amount) + '   ' + str(ratio))
                # except:
                #     pass

        # sleep
        time.sleep(interval)

        # cancel order
        for id in buy_id: 
            try:
                result = fcoin.cancel_order(id)
                if result == None:
                    logger.info('>> buy   ' + str(price_ask) + '   ' + str(amount) + '   ' + str(ratio))
                    if ratio > min_ratio:ratio -= 1
                if result['status'] == 0:
                    logger.info('submit-cancel')
                    if ratio < max_ratio:ratio += 1
            except:
                pass
        for id in sell_id:
            try:
                result = fcoin.cancel_order(id)
                if result == None:
                    logger.info('>> sell   ' + str(price_bid) + '   ' + str(amount) + '   ' + str(ratio))
                    if ratio > min_ratio:ratio -= 1
                if result['status'] == 0:
예제 #7
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("coin")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(),6)]
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.begin_balance=self.get_blance()

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        self.now_price = ticker['data']['ticker'][0]
        self.log.info("now price%s" % self.now_price )
        return self.now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance

    def save_csv(self,array):
        with open("data/trade.csv","a+",newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None

    def process(self):
        price = self.digits(self.get_ticker(),6)
        self.oldprice.append(price)
        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']
        usdt = self.dic_balance['usdt']
        
        self.log.info("usdt has--[%s]   ft has--[%s]" % (usdt.balance, ft.balance))

        order_list = self.fcoin.list_orders(symbol=self.symbol,states='submitted')['data']
        print(order_list)
        self.log.info("order trading: %s" % order_list)

        if not order_list or len(order_list) < 2:
            if usdt and abs(price/self.oldprice[len(self.oldprice)-2]-1)<0.02:
                if price*2 < self.oldprice[len(self.oldprice)-2]+self.oldprice[len(self.oldprice)-3]:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            self.fee = amount*0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                            self.type = 1
                            self.log.info('buy success price--[%s] amout--[%s] fee--[%s]' % (price,amount ,self.fee))
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.fee = amount*price*0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            self.type = 2
                            self.log.info("sell success price--[%s] amout--[%s] fee--[%s]" % (price,amount, self.fee))

            else:
                print('价格波动过大 %s' % usdt)
                self.log.info("价格波动过大%s" % usdt)
        else:
            print('system busy')
            if len(order_list) >= 1:
                self.log.info("cancel order {%s}" % order_list[-1])
                order_id = order_list[-1]['id']
                data = self.fcoin.cancel_order(order_id)
                self.log.info("cancel result {%s}" % data)
                if data:
                    if order_list[len(order_list)-1]['side'] == 'buy' and order_list[len(order_list)-1]['symbol'] == 'ftusdt':
                        self.fee = -float(order_list[len(order_list)-1]['amount'])*0.001
                    elif order_list[len(order_list)-1]['side'] == 'sell' and order_list[len(order_list)-1]['symbol'] == 'ftusdt':
                        self.fee = -float(order_list[len(order_list)-1]['amount'])*float(order_list[len(order_list)-1]['price'])*0.001
                    self.type = 3
                    self.order_id = order_id
        
    def loop(self):
        while True:
            try:
                time1 = time.time()
                self.process()
                array = [self.order_id,self.now_price,self.type,self.fee,self.symbol,time.strftime('%Y-%m-%d %H:%M:%S')]
                if type != 0:
                    self.save_csv(array)
                self.log.info("--------success-------")
                time2 = time.time()
                self.log.info("app time--%s"% str(time2-time1))
                time.sleep(3)
            except Exception as e:
                self.log.info(e)
                print(e)
            finally:
                self.reset_save_attrubute()
예제 #8
0
파일: RunAPI7.py 프로젝트: zkkxyz/Robot
    def work(self):
        global gIniQueue

        self.printLog('软件启动!')
        file = open('./ini.json')
        dic = json.loads(file.read())
        apikey = dic['apikey']
        apisecret = dic['apisecret']
        file.close()

        while gFlag:
            try:

                try:
                    ini = gIniQueue.get(block=False)
                except:
                    pass
                else:
                    str1 = ini[0]
                    str2 = ini[1]
                    num = ini[2]
                    str3 = ini[3]
                    myTime = ini[4]
                    num2 = ini[5]
                    buyFlag = ini[6]
                    tel = ini[7]
                    myTime2 = ini[8]
                    num3 = ini[9]

                    # test
                    self.printLog(str(ini))

                # file = open('./mytxt.txt', 'a+')
                fcoin = Fcoin()
                # 主号
                # fcoin.auth('', '')
                # 刷号
                fcoin.auth(apikey, apisecret, tel)
                # os.system('fskl.mp3')
                # 获取账户资产
                data = fcoin.get_balance()
                self.printLog('交易对:%s' % (str3))
                level = fcoin.get_market_depth('L20', str3)
                if ('data' not in data.keys()) or (not data['data']):
                    continue
                for i in data['data']:
                    if i['currency'] == str1:
                        my_usdt = i['balance']
                        self.printLog(str1 + '余额: ' + my_usdt)
                    if i['currency'] == str2:
                        my_ft = i['balance']
                        self.printLog(str2 + '余额: ' + my_ft)

                nowBids = level['data']['bids'][0]
                sumBids = 0
                for i in range(0, len(level['data']['bids'])):
                    if (i % 2) == 0:
                        nowBids = level['data']['bids'][i]
                        self.printLog('本次价格:%s' % (nowBids))
                    else:
                        temp_Num2 = sumBids
                        sumBids += level['data']['bids'][i]
                        self.printLog(
                            '买盘 本次数量总和:%s  本次数量:%s 上次数量总和:%s  总数量:%s' %
                            (sumBids, level['data']['bids'][i], temp_Num2,
                             num3))
                        if sumBids > num3:  #num3是输入的数
                            if i != 0:
                                sumBids = temp_Num2
                            self.printLog('本次数量总和:%s' % (sumBids))
                            if i > 0:
                                nowBids = level['data']['bids'][i - 1]
                                self.printLog('买盘本次价格:%s' % (nowBids))
                            break
                        elif sumBids == num3:
                            break

                nowAsks = level['data']['asks'][0]
                sumAsks = 0
                for i in range(0, len(level['data']['asks'])):
                    if (i % 2) == 0:
                        nowAsks = level['data']['asks'][i]
                        self.printLog('本次价格:%s' % (nowAsks))
                    else:
                        temp_Num2 = sumAsks
                        sumAsks += level['data']['asks'][i]
                        self.printLog(
                            '卖盘 本次数量总和:%s  本次数量:%s  上次数量总和:%s  总数量:%s' %
                            (sumAsks, level['data']['asks'][i], temp_Num2,
                             num3))  #sumAsks+temp_Num2 这是什么意思
                        if sumAsks > num3:  #num3是输入的数
                            if i != 0:
                                sumAsks = temp_Num2
                            self.printLog('本次数量总和:%s' % (sumAsks))
                            if i > 0:
                                nowAsks = level['data']['asks'][i - 1]
                                self.printLog('卖盘本次价格:%s' % (nowAsks))
                            break
                        elif sumAsks == num3:
                            break

                self.printLog('价格小数:%s' % (num2))
                nowResult = round(
                    (round(nowAsks, num2) + round(nowBids, num2)) / 2, num2)

                logStr = str(data)
                # self.printLog(logStr)
                # file.write(logStr+ '\n')

                nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                resultstr = fcoin.get_market_ticker(str3)
                logStr = str(resultstr)
                # self.printLog(logStr)
                # file.write(logStr+ '\n')
                wantstr = resultstr["data"]["ticker"]
                # a是买一价  b是卖一价
                a, b = wantstr[2], wantstr[4]
                # result = round(random.uniform(a, b), num2)
                result = nowResult
                logStr = "random price is:" + str(
                    result) + "now time:" + nowtime
                # self.printLog(logStr)
                # file.write(logStr+ '\n')

                #卖
                if num < float(my_ft):
                    sellop = fcoin.sell(str3, result, str(round(num, 2)))
                    if (sellop is not None) and (sellop['status'] == 0):
                        logStr = r'限价卖出成功 限价卖出%s个%s  卖出价格是%s  当前时间是%s' % (
                            num, str2, result, nowtime)
                        self.printLog(logStr)
                    else:
                        self.printLog(sellop['msg'])

                elif (num > float(my_ft)):

                    if buyFlag:
                        buyop = fcoin.buy_market(
                            str3,
                            round(
                                float(num) * float(result) -
                                float(my_ft) * float(result), 2))
                        tempFlag = False
                        if (buyop is not None) and (buyop['status'] == 3014):
                            tempFlag = True
                            temp_num = int(
                                re.search(r'\d+$', buyop['msg']).group(0))
                            buyop = fcoin.buy_market(str3, str(temp_num))
                            #
                            # if (buyop is not None) and (buyop['status'] == 0):
                            #     # print(num-float(my_ft))*(result/float(my_usdt))
                            #     logStr = r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s' % (
                            #     str(round((num - float(my_ft)) * b + (((num - float(my_ft)) * b) * 0.1), 2)), str1,
                            #     str2, nowtime)
                            #     self.printLog(logStr)
                            #     continue
                            # file.write(logStr+ '\n')
                            # else:
                            #     self.printLog(buyop['msg'])
                            #     continue

                        # buyop = fcoin.buy(str3, result,str(float(num-float(my_ft))*(result/float(my_usdt))))
                        # buyop = fcoin.buy(str3, b, str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        if (buyop is not None) and (buyop['status'] == 0):
                            # print(num-float(my_ft))*(result/float(my_usdt))
                            if not tempFlag:
                                logStr = r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s' % (
                                    str(
                                        round(
                                            float(num) * float(result) -
                                            float(my_ft) * float(result),
                                            2)), str1, str2, nowtime)
                            else:
                                logStr = r'市价补仓买入成功 市价买入%s个%s的%s  当前时间是%s' % (
                                    temp_num, str1, str2, nowtime)
                            self.printLog(logStr)
                            continue
                            # file.write(logStr+ '\n')

                        else:
                            self.printLog(buyop['msg'])
                            continue
                            # time.sleep(60*?)
                        # buyrecord = buyop["data"]

                        # sellop = fcoin.sell(str3, result, str(num))
                        # if (sellop is not None) and (sellop['status']==0):
                        #     logStr = r'限价卖出成功 卖出%s个s%  卖出价格是%s  当前时间是%s' % (num, str2,result, nowtime)
                        #     self.printLog(logStr)
                        #     # file.write(logStr+ '\n')
                        # else:
                        #     self.printLog(sellop['msg'])
                        # if sellop:
                        #     sellrecord = sellop["data"]
                    else:
                        smsResult = sms_send.send('您当前交易对数量不足,请及时处理', tel,
                                                  '44060')
                        #在这等15分钟
                        logStr = r'因为交易对数量不足程序已停止,30分钟后重新启动'
                        time.sleep(60 * 30)

                #买
                if num < float(my_usdt):
                    buyop = fcoin.buy(str3, result, str(round(num, 2)))
                    if (buyop is not None) and (buyop['status'] == 0):
                        logStr = r'限价买入成功 限价买入%s个%s  买入价格是%s  当前时间是%s' % (
                            num, str2, result, nowtime)
                        self.printLog(logStr)
                        # file.write(logStr+ '\n')
                    else:
                        self.printLog(buyop['msg'])

                    # buyrecord = buyop["data"]

                elif num > float(my_usdt):

                    if buyFlag:
                        # sell正常卖  sell_market非正常卖
                        # sellop = fcoin.sell_market(str3,  str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        sellop = fcoin.sell_market(
                            str3,
                            round(
                                (float(num) * float(result) - float(my_usdt)),
                                2))
                        # sellop = fcoin.sell_market(str3, num+(num*result)*0.01)
                        tempFlag = False
                        if (sellop is not None) and (sellop['status'] == 3014):
                            tempFlag = True
                            temp_num = int(
                                re.search(r'\d+$', sellop['msg']).group(0))
                            sellop = fcoin.buy_market(str3, str(temp_num))

                        # sellop =fcoin.sell(str3, round(a,num2), str(round(num-float(my_ft)+((num-float(my_ft))*0.1),2)))
                        if (sellop is not None) and (sellop['status'] == 0):
                            if not tempFlag:
                                logStr = r'市价补仓卖出成功 市价卖出%s个%s,当前时间是%s' % (str(
                                    round((float(num) * float(result) -
                                           float(my_usdt)))), str2, nowtime)
                            else:
                                logStr = r'市价补仓卖出成功 市价卖出%s个%s,当前时间是%s' % (
                                    temp_num + temp_num * 0.1, str2, nowtime)
                            self.printLog(logStr)
                            continue
                            # file.write(logStr+ '\n')
                        else:
                            self.printLog(sellop['msg'])
                            continue

                        # if sellop:
                        #     sellrecord = sellop["data"]

                        # buyop = fcoin.buy(str3, result, str(num))
                        # if (buyop is not None) and (buyop['status']==0):
                        #     logStr = r'限价买入成功 限价买入%s个%s  买入价格是%s  当前时间是%s' % (num,str2, result, nowtime)
                        #     self.printLog(logStr)
                        #     # file.write(logStr+ '\n')
                        # else:
                        #     self.printLog(buyop['msg'])
                        # # buyrecord = buyop["data"]
                    else:
                        smsResult = sms_send.send('您当前交易对数量不足,请及时处理', tel,
                                                  '44060')
                        logStr = r'因为交易对数量不足程序已停止,30分钟后重新启动'
                        time.sleep(60 * 30)
                time.sleep(myTime)

                # 获取订单列表
                if buyFlag:
                    rol = fcoin.list_orders(str3, 'submitted,partial_filled')
                    if ('data' not in rol.keys()) or (not rol['data']):
                        continue
                    lastTime = rol['data'][len(rol['data']) - 1]['created_at']
                    lastTime = int(re.sub(r'\d{3}$', '', str(lastTime)))
                    nowTime = int(time.time())

                    if not buyFlag:
                        if (nowTime - lastTime) > (myTime):
                            smsResult = sms_send.send('您当前有超过5分钟未成交的订单,请及时处理',
                                                      tel, '44060')
                    else:
                        # 这里加not true的else
                        if buyFlag:
                            for p in rol["data"]:
                                if p["side"] == "buy":
                                    lastTime = p['created_at']
                                    lastTime = int(
                                        re.sub(r'\d{3}$', '', str(lastTime)))
                                    nowTime = int(time.time())
                                    if (nowTime - lastTime) > (myTime2):
                                        # 市价卖
                                        sellamount = round(
                                            float(p["amount"]) -
                                            float(p["filled_amount"]), 2)
                                        temptemp_result = fcoin.cancel_order(
                                            p["id"])
                                        if (temptemp_result is None) or (
                                                temptemp_result['status'] !=
                                                0):
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价买入订单取消失败,因为已取消,现在时间是:" + nowtime
                                        else:
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价买入订单取消成功,现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        file.write(logStr + '\n')

                                        temptemp_result1 = fcoin.buy_market(
                                            str3, sellamount)
                                        if (temptemp_result1 is None) or (
                                                temptemp_result1['status'] !=
                                                0):
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价买入订单取消失败,因为已取消,现在时间是:" + nowtime
                                        else:
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价买入订单取消成功,现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        # file.write(logStr+ '\n')

                                elif p["side"] == "sell":
                                    lastTime = p['created_at']
                                    lastTime = int(
                                        re.sub(r'\d{3}$', '', str(lastTime)))
                                    nowTime = int(time.time())
                                    if (nowTime - lastTime) > (myTime2):
                                        # 市价卖
                                        sellamount = round(
                                            float(p["amount"]) -
                                            float(p["filled_amount"]), 2)
                                        temptemp_result = fcoin.cancel_order(
                                            p["id"])
                                        if (temptemp_result is None) or (
                                                temptemp_result['status'] !=
                                                0):
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价卖出订单取消失败,因为已取消,现在时间是:" + nowtime
                                        else:
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 限价卖出订单取消成功,现在时间是:" + nowtime

                                        self.printLog(logStr)
                                        file.write(logStr + '\n')

                                        temptemp_result = fcoin.sell_market(
                                            str3, sellamount)
                                        if (temptemp_result is None) or (
                                                temptemp_result['status'] !=
                                                0):
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单 市价卖出结果失败,因为已取消,现在时间是:" + nowtime
                                        else:
                                            logStr = "检测到有超过" + str(
                                                myTime2
                                            ) + "秒未完成订单  市价卖出结果成功,现在时间是:" + nowtime
                                        self.printLog(logStr)
                                        file.write(logStr + '\n')

                                # elif ['side']=='buy':
                                #     lastTime = p['created_at']
                                #     lastTime = int(re.sub(r'\d{3}$', '', str(lastTime)))
                                #     nowTime = int(time.time())
                                #     if (nowTime - lastTime) > (myTime2):
                                #         # 市价买
                                #         sellamount = round(float(p["amount"]) - float(p["filled_amount"]), 2)
                                #         temptemp_result = fcoin.buy_market(str3, sellamount)
                                #         if (temptemp_result is None) or (temptemp_result['status'] != 0):
                                #             logStr = "检测到有超过" + str(myTime2) + "秒未完成订单 市价买入结果失败,因为已取消,现在时间是:" + nowtime
                                #         else:
                                #             logStr = "检测到有超过" + str(myTime2) + "秒未完成订单  市价买入结果成功,现在时间是:" + nowtime
                                #         self.printLog(logStr)
                                #         file.write(logStr + '\n')
                                # file.write(logStr+ '\n')

                # isemprol = fcoin.list_orders('ftusdt', 'submitted,partial_filled')
                # print(isemprol)
                # time.sleep(myTime)
                # if len(isemprol["data"]) != 0:
                #     flag = False
                #     # os.system('fskl.mp3')
                # file.close()
                # # 执行完等3秒继续循
                # time.sleep(1)

            except Exception as e:
                raise e
                time.sleep(myTime)

        self.printLog('软件结束!')