示例#1
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.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0
        self.buy_price =0.0
        self.sell_price = 0.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)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.now_price

    def get_must_sell_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.buy_price

    def get_must_buy_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.sell_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 server_time(self):
        now = datetime.datetime.fromtimestamp(int(self.fcoin.get_server_time()/1000))
        return now

    def dateDiffInSeconds(self, date1, date2):
        timedelta = date2 - date1
        return timedelta.days*24*3600 + timedelta.seconds
        
    def do_hour(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        print('ft:%s usdt:%s' % (ft.available,usdt.available))

        if usdt.available > 10:
            price = self.digits(self.get_must_buy_ticker(),6)
            amount = self.digits(usdt.available / price * 0.98, 2)
            if amount >= 5:
                self.log.info('buy price--[%s] amout--[%s]' % (price,amount))
                data = self.fcoin.buy(self.symbol, price, amount, 'limit')
                if data:
                    self.order_id = data['data']
                    self.log.info('buy order success price--[%s] amout--[%s]' % (price,amount))

                    server_time = self.server_time()
                    start_time = server_time.replace(minute=58, second=50,microsecond=0)
                    sleep_seconds = self.dateDiffInSeconds(server_time, start_time)
                    if sleep_seconds > 1:
                        time.sleep(sleep_seconds)
                    
                    self.dic_balance = self.get_blance()
                    ft = self.dic_balance["ft"]
                    usdt = self.dic_balance["usdt"]
                    
                    new_price = price
                    while new_price <= price:
                        new_price = self.digits(self.get_must_sell_ticker(),6)
                        time.sleep(5)

                    if new_price > price:
                        self.log.info('sell price--[%s] amout--[%s]' % (price,amount))
                        data = self.fcoin.sell(self.symbol, new_price, amount,'limit')
                        self.log.info('sell order success price--[%s] amout--[%s]' % (new_price, amount))


    def loop(self):
        while True:
            try:
                server_time = self.server_time()
                start_time = server_time.replace(minute=50, second=0,microsecond=0)
                sleep_seconds = self.dateDiffInSeconds(server_time, start_time)
                if sleep_seconds > 1:
                    print("servertime: %s , starttime: %s , sleep: %s" % (server_time,start_time,sleep_seconds))
                    time.sleep(sleep_seconds)
                    self.do_hour()
                else:
                    time.sleep(60)

            except Exception as e:
                self.log.info(e)
                print(e)
            finally:
                self.reset_save_attrubute()
示例#2
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)
示例#3
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)
示例#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.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)
示例#6
0
from fcoin3 import Fcoin
import os

fcoin = Fcoin()

print(fcoin.get_symbols())

print(fcoin.get_currencies())

api_key = os.environ["FCOIN_API_KEY"]
api_sec = os.environ["FCOIN_API_SECRET"]

fcoin.auth(api_key, api_sec)

print(fcoin.get_balance())

print(fcoin.buy('fteth', 0.0001, 10))
#print(fcoin.sell('fteth', 0.002, 5))
#print(fcoin.cancel_order('6TfBZ-eORp4_2nO5ar6zhg0gLLvuWzTTmL1OzOy9OYg='))
#print(fcoin.get_candle('M1','fteth'))
示例#7
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)
示例#8
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
        self.buy_price = 0.0
        self.sell_price = 0.0
        self.executor = ThreadPoolExecutor(max_workers=4)

    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)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.now_price

    def get_must_sell_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.buy_price

    def get_must_buy_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.sell_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 syn_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 jump(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        if usdt.available > 10:
            price = self.digits(self.get_must_buy_ticker(), 6)
            amount = self.digits(usdt.available / price * 0.99, 2)
            if amount >= 5:
                data = self.fcoin.buy(self.symbol, price, amount, 'market')
                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))

                    time.sleep(270)

                    self.dic_balance = self.get_blance()
                    ft = self.dic_balance["ft"]
                    usdt = self.dic_balance["usdt"]

                    new_price = price
                    while new_price <= price:
                        new_price = self.digits(self.get_must_sell_ticker(),
                                                amount)
                        time.sleep(5)

                    if new_price > price:
                        data = self.fcoin.sell(self.symbol, price, amount,
                                               'market')
                        self.log.info(
                            'sell success price--[%s] amout--[%s] fee--[%s]' %
                            (price, amount, self.fee))
示例#9
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()
示例#10
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('软件结束!')
示例#11
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.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0
        self.buy_price = 0.0
        # 正在卖出
        self.in_sell = False
        # 卖出价格
        self.sell_price = 0.0
        # 价格队列
        self.price_queue = []
        # 验证是否卖出价格
        self.check_sell_price = 0.0
        # 总共的增量
        self.total_increment = 0.0
        # 服务器时间
        self.diff_server_time = None

        stategy_quick.set_app(self)
        candle_data.set_app(self)

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

    def get_ticker(self):
        if self.sell_price is None:
            self.get_market_ticker()
        return self.now_price

    def get_must_sell_ticker(self):
        if self.sell_price is None:
            self.get_market_ticker()
        return self.buy_price

    def get_must_buy_ticker(self):
        if self.sell_price is None:
            self.get_market_ticker()
        return self.sell_price

    def get_market_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]

    # 获取当前用户持币信息
    def get_blance(self):
        if self.dic_blance is None:
            self.syn_blance()
        return self.dic_blance

    # 同步持币信息
    def syn_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']))
        self.dic_blance = dic_blance
        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 get_server_time(self):
        if self.diff_server_time is None:
            self.synchronize_time()
        return datetime.datetime.fromtimestamp(
            int((int(datetime.datetime.now().timestamp() * 1000) +
                 self.diff_server_time) / 1000))

    # 同步时间
    def synchronize_time(self):
        # self.server_time = datetime.datetime.fromtimestamp(int(self.fcoin.get_server_time() / 1000))
        self.diff_server_time = int(self.fcoin.get_server_time()) - int(
            datetime.datetime.now().timestamp() * 1000)
        # print(self.diff_server_time)

    def dateDiffInSeconds(self, date1, date2):
        timedelta = date2 - date1
        return timedelta.days * 24 * 3600 + timedelta.seconds

    def do_hour(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        print('ft:%s usdt:%s' % (ft.available, usdt.available))

        if usdt.available > 50:
            # 买入ft
            price = self.digits(self.get_must_buy_ticker(), 6)
            amount = self.digits(usdt.available / price * 0.98, 2)
            if amount >= 5:
                self.log.info('buy price--[%s] amout--[%s]' % (price, amount))
                data = self.fcoin.buy(self.symbol, price, amount, 'limit')
                if data:
                    self.order_id = data['data']
                    self.log.info('buy order success price--[%s] amout--[%s]' %
                                  (price, amount))

                    server_time = self.get_server_time()
                    start_time = server_time.replace(minute=58,
                                                     second=50,
                                                     microsecond=0)
                    sleep_seconds = self.dateDiffInSeconds(
                        server_time, start_time)
                    if sleep_seconds > 1:
                        time.sleep(sleep_seconds)

                    self.dic_balance = self.get_blance()
                    ft = self.dic_balance["ft"]
                    usdt = self.dic_balance["usdt"]

                    new_price = price
                    while new_price <= price:
                        new_price = self.digits(self.get_must_sell_ticker(), 6)
                        time.sleep(5)

                    if new_price > price:
                        self.log.info('sell price--[%s] amout--[%s]' %
                                      (price, amount))
                        data = self.fcoin.sell(self.symbol, new_price, amount,
                                               'limit')
                        self.log.info(
                            'sell order success price--[%s] amout--[%s]' %
                            (new_price, amount))
        else:

            self.sell_ft()

    # 查找到合理的卖点
    def get_sell_point(self):
        pass

    def get_sell_count(self):
        return config.sell_count

    # 卖出ft
    def sell_ft(self):
        # 卖出ft

        #       1)未持续上涨,直接卖出
        #       2)持续上涨,查找高点
        if self.get_server_time().minute < 5 and not self.in_sell:
            self.in_sell = True
            # 1、查看时间区间是在预期范围 01
            if self.get_ticker() > self.check_sell_price:
                # 2、查找合理点位卖出,
                data = self.fcoin.sell(self.symbol, self.get_sell_point(),
                                       self.get_sell_count(), 'limit')

                # 让订单卖出
                while (True):
                    # 获取订单状态
                    is_done = True
                    #
                    if is_done:
                        self.sell_done = True
                        break
                    else:
                        # 超过时间判断
                        # 超过时间重新下单
                        pass

        self.in_sell = False

    def get_buy_point(self):
        pass

    def get_sell_count(self):
        pass

    # 买入ft,直到买入成功为止
    def buy_ft(self):
        # 根据时间获取买入策略
        # 已经超过
        # 如果已经超过买入点,默认检测5分钟不够买,下降趋势情况下,超过根据涨跌获取买入点
        pass

    def get_price_queue(self):
        data = run.fcoin.get_candle("M1", run.symbol)
        self.price_queue = []
        for item in data['data']:
            self.price_queue.append(item['close'])

        trades_1 = '#'
        trades_2 = '#'
        trades_3 = '#'
        trades_5 = '#'
        trades_10 = '#'
        trades_20 = '#'
        trades_30 = '#'
        trades_60 = '#'
        # 1分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[1]
        trades_1 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 2分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[2]
        trades_2 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 3分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[3]
        trades_3 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 5分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[5]
        trades_5 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 10分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[10]
        trades_10 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 20分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[20]
        trades_20 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 30分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[30]
        trades_30 = self.digits((new_price - old_price) / old_price * 100, 6)
        # 60分钟
        new_price = self.price_queue[0]
        old_price = self.price_queue[60]
        trades_60 = self.digits((new_price - old_price) / old_price * 100, 6)

        print(
            '数据行情(百分比) 1m--[%s] 2m--[%s] 3m--[%s] 5m--[%s] 10m--[%s] 20m--[%s] 30m--[%s] 60m--[%s]'
            % (str(trades_1), str(trades_2), str(trades_3), str(trades_5),
               str(trades_10), str(trades_20), str(trades_30), str(trades_60)))

    def average(self, array):
        total = 0.0
        n = len(array)
        for num in array:
            total += num
        return 1.0 * total / n

    # 增长量计算
    def increment(self):
        data = self.fcoin.get_candle("H1", run.symbol)
        for item in data['data']:
            timeArray = time.localtime(item['id'])
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            # print("%s ----- %s" % (otherStyleTime, item))
        total_increment = 0
        for index in range(self.get_server_time().hour):
            new_price = data['data'][index + 1]['close']
            # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['data'][index+ 1]['id'])))
            old_price = data['data'][index + 1 + 24]['close']
            total_increment += (new_price - old_price) / old_price
        self.total_increment = total_increment
        print(total_increment)
        pre_date_data = []
        max_data = []
        min_data = []
        cur_hour = self.get_server_time().hour
        for index in range(24 + cur_hour):
            cur_data = data['data'][index]
            pre_date_data.append(cur_data['close'])
            pre_date_data.append(cur_data['high'])
            pre_date_data.append(cur_data['low'])

            max_data.append(cur_data['high'])
            min_data.append(cur_data['low'])

            # print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['data'][index + cur_hour]['id'])))

        # 变化系数计算
        cur_change_data = []
        pre_change_data = []
        for index in range(12):
            cur_data = data['data'][index]
            pre_data = data['data'][index + 24]
            cur_change_data.append(cur_data['close'])
            pre_change_data.append(pre_data['close'])

        change_price = np.average(np.array(cur_change_data)) / np.average(
            np.array(pre_change_data))
        print(change_price)

        np_data = np.array(pre_date_data)
        np_data_max = np.array(max_data)
        np_data_min = np.array(min_data)

        np_data_max.sort()
        max_avg_price = np.average(np_data_max[len(np_data_max) - 3:])
        np_data_min.sort()
        min_avg_price = np.average(np_data_min[0:3])
        # 极差
        # print(ptp(data))
        # print(var(data))
        # print(std(data))
        # print(mean(data) / std(data))
        # print(data.min())
        # print(median(data))
        # print(mean(data))
        # print(data)
        median_data = np.average(np_data)
        print(np_data)
        print(median_data)
        print(max_avg_price)
        print(min_avg_price)
        self.check_min_sell_price = (
            median_data - (median_data - min_avg_price) * 0.3) * change_price
        self.check_could_sell_price = (
            median_data + (max_avg_price - median_data) * 0.7) * change_price
        self.check_max_buy_price = (
            median_data + (max_avg_price - median_data) * 0.3) * change_price
        self.check_could_buy_price = (
            median_data - (median_data - min_avg_price) * 0.7) * change_price

        print(self.check_min_sell_price)
        print(self.check_could_sell_price)
        print(self.check_max_buy_price)
        print(self.check_could_buy_price)

    # 获取区间
    def get_interval(self):
        print(candle_data.get_candle_M1())

    # 计算区间
    def calculation_interval(self):
        candle_M1 = candle_data.get_candle_M1()
        candle_M1_data = candle_M1['data']
        for index in range(60):
            candle_M1_data[60 - 1 - index]

    # 改为定时任务
    def loop(self):

        stategy_quick.schedule()
        candle_data.schedule()
        # 开启卖出线程
        # schedule.every(2).seconds.do(self.get_interval)
        schedule.every(1).seconds.do(self.get_market_ticker)
        # schedule.every(10).seconds.do(self.sell_ft)
        # schedule.every(30).seconds.do(self.get_price_queue)
        # schedule.every(10).seconds.do(self.print_price_queue)
        while True:
            schedule.run_pending()
            time.sleep(1)
示例#12
0
from fcoin3 import Fcoin
import random
import time
import datetime
import os

while True:
    file = open('./mytxt.txt', 'a+')

    fcoin = Fcoin()

    fcoin.auth('xxx', 'xxx')
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    resultstr = fcoin.get_market_ticker("ftusdt")
    file.write(str(resultstr) + '\n')
    wantstr = resultstr["data"]["ticker"]
    a, b = wantstr[2], wantstr[4]
    result = round(random.uniform(a, b), 6)
    file.write("random price is:" + str(result) + "now time:" + nowtime + '\n')

    file.write("buy status is:" + str(fcoin.buy('ftusdt', result, 10)) +
               " now time:" + nowtime + '\n')
    file.write("sell status is:" + str(fcoin.sell('ftusdt', result, 10)) +
               " now time:" + nowtime + '\n')

    file.close()
    #执行完等5秒继续循环
    time.sleep(5)