Beispiel #1
0
def sync_depth():
    fcoin = Fcoin()
    # fcoin.auth('key ', 'secret')
    sDir = os.path.join(os.path.abspath('..'), '..', 'Fcoin_DL')
    stime = time.strftime('%Y%m%d', time.localtime())
    rootn = 'depth'
    level = 'L20'
    dirname = '{0}{1}'.format(rootn, level)
    # 获取最新的深度明细
    # 买(卖)1价, 买(卖)1量
    depth_head = ['买1价', '买的量数', '卖1价', '卖的量数']
    depth_flag = '买1价'
    # asks_head = ['卖1价','卖的量数']
    # asks_flag = '卖1价'
    for sy in config.sylist:
        # for original data
        sTfile = '{0}_{1}_{2}'.format(stime, sy, '{0}{1}'.format(rootn, '.txt'))
        sTfilepath = os.path.join(sDir, dirname, sTfile)

        dpfile = '{0}_{1}_{2}'.format(stime, sy, '{0}{1}'.format(rootn, '.csv'))
        dpspath = os.path.join(sDir, dirname, dpfile)

        rdata = fcoin.get_market_depth(level, sy)
        depthinfo = rdata['data']  # 20 档行情深度 for iask in depthinfo['asks']:
        bidlists = depthinfo['bids']
        print(bidlists)
        asklists = depthinfo['asks']
        print(asklists)
        idp = 0

        nask = len(depthinfo['asks'])
        # nbid = len(depthinfo['bids'])
        rFind = False
        while idp < nask:
            if os.path.exists(dpspath):
                with open(dpspath, 'r', encoding='utf-8') as f:
                    first_line = f.readline()  # 取第一行
                    rFind = depth_flag in first_line
            with open(dpspath, 'a+', encoding='utf-8', newline='') as f:
                w = csv.writer(f)
                balist = []
                # balist = list(bidlists[idp:idp + 2] )
                balist.extend(bidlists[idp:idp + 2])
                balist.extend(asklists[idp:idp + 2])
                if rFind is True:
                    w.writerow(balist)
                    idp += 2

                else:
                    w.writerow(depth_head)
                    w.writerow(balist)
                    idp += 2
        f.close()

        # write original data to txt files
        with open(sTfilepath, 'a+', encoding='utf-8') as tf:
            tf.writelines(json.dumps(rdata) + '\n')
            tf.close()
def getMidPrice():
    """
    获取btc_usdt的深度行情
    :return:
    """
    public_ticker = Fcoin()

    result, data = public_ticker.get_market_depth("L20", "btcusdt")
    if data["status"] == 0:
        info = data["data"]

        bids_data = info["bids"]
        asks_data = info["asks"]

        bids_data = [float(x) for x in bids_data]
        asks_data = [float(x) for x in asks_data]

        llen_bids = len(bids_data)
        llen_asks = len(asks_data)

        new_bids_arr = []
        for i in range(int(llen_bids / 2)):
            new_bids_arr.append([bids_data[2 * i], bids_data[2 * i + 1]])

        new_asks_arr = []
        for i in range(int(llen_asks / 2)):
            new_asks_arr.append([asks_data[2 * i], asks_data[2 * i + 1]])

        sort_bids_data = sorted(new_bids_arr,
                                key=lambda price_pair: price_pair[0])
        sort_asks_data = sorted(new_asks_arr,
                                key=lambda price_pair: price_pair[0])

        sort_bids_data.reverse()

        bidPrice1, bidVolume1 = sort_bids_data[0]
        askPrice1, askVolume1 = sort_asks_data[0]

        midPrice = (bidPrice1 + askPrice1) / 2.0

        midPrice = round(midPrice, 2)

        return (midPrice, bidPrice1, askPrice1)
    else:
        return None, None, None
Beispiel #3
0
class app():
    def __init__(self):
        self.key = config.key
        self.secret = config.secret

        self._log = None
        self.dic_balance = defaultdict(lambda: None)
        self.order_list = defaultdict(lambda: None)
        self.stop = False

        self.buy_order_id = None
        self.sell_order_id = None
        self.time_order = time.time()

        self.db = mongodb()
        self.fcoin = Fcoin()
        self.fcoin.auth(self.key, self.secret)
        self._init_log()

    def _init_log(self):
        self._log = logging.getLogger(__name__)
        self._log.setLevel(level=logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(message)s')

        handler = logging.FileHandler("app.log")
        handler.setLevel(logging.INFO)
        handler.setFormatter(formatter)
        self._log.addHandler(handler)


        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(formatter)
        self._log.addHandler(console)

    #查询订单
    def get_orders(self, symbol, states, limit=1):
        '''
        :param symbol:
        :param states: submitted/partial_filled/partial_canceled/canceled/pending_cancel/filled
        :return:
        '''
        success, data = self.fcoin.list_orders(symbol=symbol, states=states, limit=limit)
        if success:
            return data['data']
        else:
            print(data)
            return None
    #获取余额
    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        success, data = self.fcoin.get_balance()
        if success:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance
    #精度
    def digits(self,num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp
    #过程
    def process(self):
        if self.buy_order_id is None and self.sell_order_id is None:
            success, data = self.fcoin.get_market_depth('L20', config.symbol)
            if success:
                bids = data['data']['bids']  # 买
                asks = data['data']['asks']  # 卖
                total_bids = 0
                total_asks = 0

                for i in range(3):
                    total_bids += bids[2*i - 1]
                    total_asks += asks[2*i - 1]

                buy_price = bids[0]
                buy_amount = bids[1]

                sell_price = asks[0]
                sell_amount = asks[1]

                usdt = self.dic_balance['usdt']
                btc = self.dic_balance['btc']
                amount = 0
                price = 0
                order = None
                if btc:
                    r = self.db.get('buy',buy_price)
                    if r:
                        amount = self.digits(r['amount'], 4)
                        order = {'id': r['_id'], 'amount': amount, 'price': r['price']}

                    #if btc.available >= 0.001 and amount < 0.001:
                    #    amount = self.digits(btc.available, 4)

                    if amount >= 0.001:
                        price = self.digits(sell_price, 2)
                        success, data = self.fcoin.sell(config.symbol, price, amount)#卖
                        if success:
                            self.time_order = time.time()
                            self.sell_order_id = data['data']
                            self._log.info('挂卖单成功[%s:%s]' % (amount, price))
                            if order:
                                self.order_list[self.sell_order_id] = order
                            return
                if usdt:

                    if btc and btc.available >= config.limit_account:
                        self.dic_balance = self.get_blance()
                        self._log.info('余额度超过%s个BTC,停止买入[%s]' % (config.limit_account, btc.available))
                        return

                    if usdt.available > buy_price * config.max_amount:
                        amount = config.max_amount if total_bids > config.total_amount and total_asks > config.total_amount else config.min_amount
                    else:
                        amount = usdt.available/buy_price
                    amount = self.digits(amount, 4)
                    price = self.digits(buy_price, 2)
                    success, data = self.fcoin.buy(config.symbol, price, amount)#买
                    if success:
                        self.time_order = time.time()
                        self.buy_order_id = data['data']
                        self._log.info('挂买单成功[%s:%s]' % (amount, price))

                else:
                    self._log.info('余额错误')
                    self.dic_balance = self.get_blance()
        else:
            if self.sell_order_id:
                success, data = self.fcoin.get_order(self.sell_order_id)
                if success:
                    state = data['data']['state']
                    amount = float(data['data']['filled_amount'])

                    if state in ('filled','partial_canceled'):
                        order = self.order_list[self.sell_order_id]
                        if order:
                            self.db.update( order['id'], amount)

                    if state == 'filled':
                        self.sell_order_id = None
                        self._log.info('卖单已成交')
                        self.dic_balance = self.get_blance()

                    elif state == 'canceled' or state == 'partial_canceled':
                        self.sell_order_id = None
                        self._log.info('卖单已撤单')
                        self.dic_balance = self.get_blance()

                    elif state not in ('pending_cancel'):
                        if time.time() - self.time_order >= 15:
                            self.fcoin.cancel_order(self.sell_order_id)
                            self._log.info('15秒超时撤单')

            if self.buy_order_id:
                success, data = self.fcoin.get_order(self.buy_order_id)
                if success:
                    state = data['data']['state']
                    amount = float(data['data']['filled_amount']) - float(data['data']['fill_fees'])
                    price = float(data['data']['price'])

                    if amount > 0 and state in ('filled','partial_canceled'):
                        self.db.add('buy', price, amount)

                    if state == 'filled':
                        self.buy_order_id = None
                        self._log.info('买单已成交')
                        self.dic_balance = self.get_blance()

                    elif state == 'canceled' or state == 'partial_canceled':

                        self.buy_order_id = None
                        self._log.info('买单已撤单')
                        self.dic_balance = self.get_blance()

                    elif state not in ('pending_cancel'):
                        if time.time() - self.time_order >= 15:
                            self.fcoin.cancel_order(self.buy_order_id)
                            self._log.info('15秒超时撤单')

    def task(self):

        dic = self.get_orders(config.symbol, 'submitted', 20)
        for item in dic:
            self.fcoin.cancel_order(item['id'])
        self.dic_balance = self.get_blance()

        self.loop()

    def loop(self):
        while not self.stop:
            self.process()
            time.sleep(1)
Beispiel #4
0
# 买(卖)1价, 买(卖)1量
# The ask price is what sellers are willing to take for it.
# If you are selling a stock, you are going to get the bid price,
# if you are buying a stock you are going to get the ask price.
bids_head = ['买1价','买的量数']
bids_flag = '买1价'
asks_head = ['卖1价','卖的量数']
asks_flag = '卖1价'
for sy in sylist:
    bidsfile = '{0}_{1}_{2}'.format(stime,sy, 'bids_depth.csv')
    bidspath = os.path.join(sDir, bidsfile)

    asksfile = '{0}_{1}_{2}'.format(stime, sy, 'asks_depth.csv')
    askspath = os.path.join(sDir, asksfile)

    depthinfo = fcoin.get_market_depth('L20',sy)['data']# 20 档行情深度 for iask in depthinfo['asks']:
    bidlists = depthinfo['bids']
    print(bidlists)
    asklists = depthinfo['asks']
    print(asklists)
    nask = len(depthinfo['asks'])
    nbid = len(depthinfo['bids'])
    iask = 0
    rFindasks = False
    while iask < nask/2:
        if os.path.exists(askspath):
            with open(askspath, 'r', encoding='utf-8') as f:
                first_line = f.readline()  # 取第一行
                rFindasks = asks_flag in first_line
        with open(askspath, 'a+', encoding='utf-8',newline='') as f:
            w = csv.writer(f)
Beispiel #5
0
balance_eth = 0

for data in balance["data"]:
    if(data["currency"] == "usdt"):
        balance_usdt = float(data["available"])
    if(data["currency"] == "ft"):
        balance_ft = float(data["available"])
    if(data["currency"] == "eth"):
        balance_eth = float(data["available"])


print("balance-FT  :"+str(balance_ft))
print("balance-USDT:"+str(balance_usdt))
print("balance-ETH  :"+str(balance_eth))
'''
depth_ftusdt = fcoin.get_market_depth("L20", "ftusdt")
depth_fteth = fcoin.get_market_depth("L20", "fteth")
depth_ethusdt = fcoin.get_market_depth("L20", "ethusdt")

#float('%.4g' % (balance_ft))
max = 0
min = 10000
index_max = -1
index_min = -1

####### buy algo #######
if (depth_ftusdt["data"]["asks"][0] < min):
    min = depth_ftusdt["data"]["asks"][0]
    index_min = 1
if (depth_fteth["data"]["asks"][0] * depth_ethusdt["data"]["asks"][0] < min):
    min = depth_fteth["data"]["asks"][0] * depth_ethusdt["data"]["asks"][0]