Exemple #1
0
print('ooo')
exit(0)

# 取得当前账户信息
print("取得当前账户信息: ")
acinfo =  fcoin.get_balance()
print(acinfo)
sfile = '{0}_{1}'.format(stime, 'acbalance.csv')
sfilepath = os.path.join(sDir,sfile)
dataframe = pd.DataFrame(acinfo,index=[0])
dataframe.to_csv(sfilepath,index=False,sep=',')
exit(0)
# symbol 表示对应交易币种. 所有币种区分的 topic 都在 topic 末尾
print('取得symbol: ')
syminfo = fcoin.get_symbols()
rFind = False
sfile = '{0}_{1}'.format(stime, 'allsyminfo.csv')
sfilepath = os.path.join(sDir,sfile)
sflag = 'amount_decimal'
for ones in syminfo:
    print(ones)
    if os.path.exists(sfilepath):
        with open(sfilepath, 'r', encoding='utf-8') as f:
            first_line = f.readline()  # 取第一行
            rFind = sflag in first_line
    with open(sfilepath, 'a+', encoding='utf-8', newline='') as f:
        w = csv.writer(f)
        if rFind is True:
            vlist = list(ones.values())
            w.writerow(vlist)
class ArbitrageRobot(object):
    """docstring for Robot"""
    def __init__(self):
        self.fcoin = Fcoin(api_key, api_secret)
        self.price_decimals = {}
        self.amount_decimals = {}
        self.tickers = {}
        pd.set_option('precision', 10)
        self.time_last_call = time.time()

    # 截取指定小数位数
    def trunc(self, f, n):
        return round(f, n)
        # return math.floor(f*10**n)/10**n

    def ticker_handler(self, message):
        # print(message)
        if 'ticker' in message:
            symbol = message['type'].split('.')[1]
            self.tickers[symbol] = message['ticker']
            ticker_queue.put(self.tickers, block=False)
            logging.debug("get ticker")
            # logging.info("ticker message: {}".format(message))
        else:
            logging.debug("ticker message: {}".format(message))

    def symbols_action(self):
        all_symbols = self.fcoin.get_symbols()
        for symbol in symbol_pairs:
            for info in all_symbols:
                if symbol == info['name']:
                    self.price_decimals[symbol] = int(info['price_decimal'])
                    self.amount_decimals[symbol] = int(info['amount_decimal'])
                    break
        logging.info("price_decimals: {}".format(self.price_decimals))
        logging.info("amount_decimals: {}".format(self.amount_decimals))

    # 买操作
    def buy_action(self, this_symbol, this_price, this_amount, type="limit"):
        # this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        buy_result = self.fcoin.buy(this_symbol, this_price, this_amount, type)
        # print('buy_result is', buy_result)
        buy_order_id = buy_result['data']
        if buy_order_id:
            lprint("买单 {} 价格成功委托, 订单ID {}".format(this_price, buy_order_id))
        return buy_order_id

    # 卖操作
    def sell_action(self, this_symbol, this_price, this_amount, type="limit"):
        # this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        sell_result = self.fcoin.sell(this_symbol, this_price, this_amount,
                                      type)
        # print('sell_result is: ', sell_result)
        sell_order_id = sell_result['data']
        if sell_order_id:
            lprint("卖单 {} 价格成功委托, 订单ID {}".format(this_price, sell_order_id))
        return sell_order_id

    def strategy(self, type, pricedf, amount):
        # 从zipeth开始交易, 因为它成交量最小
        # print('使用套利策略')
        self.time_last_call = time.time()
        if type == 1:
            # usdtamount = amount*pricedf["ethusdt"]
            zipamount = amount / pricedf["zipeth"]

            thread1 = threading.Thread(target=self.sell_action,
                                       args=("zipeth", pricedf["zipeth"],
                                             zipamount))
            thread2 = threading.Thread(target=self.buy_action,
                                       args=("zipusdt", pricedf["zipusdt"],
                                             zipamount))
            thread3 = threading.Thread(target=self.sell_action,
                                       args=("ethusdt", pricedf["ethusdt"],
                                             amount))
            thread1.start()
            thread2.start()
            thread3.start()
        elif type == 2:
            zipamount = amount / pricedf["zipeth"]
            # usdtamount = amount*pricedf["ethusdt"]

            thread1 = threading.Thread(target=self.buy_action,
                                       args=("zipeth", pricedf["zipeth"],
                                             zipamount))
            thread2 = threading.Thread(target=self.sell_action,
                                       args=("zipusdt", pricedf["zipusdt"],
                                             zipamount))
            thread3 = threading.Thread(target=self.buy_action,
                                       args=("ethusdt", pricedf["ethusdt"],
                                             amount))
            thread1.start()
            thread2.start()
            thread3.start()

    def trade(self, tickers=None):
        """套利策略,寻找一个三元pair,看是不是满足套利规则。
    ETH/USDT, ZIP/ETH, ZIP/USDT
    ethusdt买一价 * zipeth买一价 / zipusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程:usdt买zip,卖zip换回eth,卖eth换回usdt
    zipusdt买一价 / zipeth卖一价 / ethusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程为:usdt买eth,eht买zip,卖zip换回usdt
    买一下标为2, 卖一下标为4"""
        # time.sleep(second)
        amount = _ethamount

        self_tickers = tickers
        if tickers == None:
            self_tickers = self.tickers

        if len(self_tickers) == len(symbol_pairs):
            info_df = pd.DataFrame(self_tickers).T
            # 买一卖一的均价
            info_df["price"] = (info_df[2] + info_df[4]) / 2

            taoli1 = info_df.loc["ethusdt", 2] * \
             info_df.loc["zipeth", 2] / info_df.loc["zipusdt", 4]
            taoli2 = info_df.loc["zipusdt", 2] / \
             info_df.loc["zipeth", 4] / info_df.loc["ethusdt", 4]

            if taoli1 > difference:
                info_df["price"] = info_df[2]
                info_df.loc["zipusdt", "price"] = info_df.loc["zipusdt", 4]
                if is_use_amount:
                    if info_df.loc["ethusdt", 3] < _halfeth or info_df.loc[
                            "zipusdt",
                            5] < _halfzip or info_df.loc["zipeth",
                                                         3] < _halfzip:
                        lprint('挂单量太小,本次无法套利 方式一', logging.DEBUG)
                        return

                lprint("满足套利条件1 套利值为{:.4}‰".format(taoli1 * 1000 - 1000))
                self.strategy(1, info_df.price, amount)
                lprint("zipeth卖价:{} zipusdt买价:{} ethusdt卖价:{}".format(
                    info_df.price["zipeth"], info_df.price["zipusdt"],
                    info_df.price["ethusdt"]))
                time.sleep(second)

            elif taoli2 > difference:
                info_df["price"] = info_df[4]
                info_df.loc["zipusdt", "price"] = info_df.loc["zipusdt", 2]
                if is_use_amount:
                    if info_df.loc["ethusdt", 5] < _halfeth or info_df.loc[
                            "zipusdt",
                            3] < _halfzip or info_df.loc["zipeth",
                                                         5] < _halfzip:
                        lprint('挂单量太小,本次无法套利 方式二', logging.DEBUG)
                        return
                    # else:
                    # 	if is_mutable_amount:
                    # 		amount = min(rates) * amount
                    # 		if amount > maxamount:
                    # 			amount = maxamount
                    # 		lprint("每单金额{}eth,最小利差{:.2}‰".format(amount, (difference-1)*1000))

                lprint("满足套利条件2 套利值比为{:.4}‰".format(taoli2 * 1000 - 1000))
                self.strategy(2, info_df.price, amount)
                lprint("zipeth买价:{} zipusdt卖价:{} ethusdt买价:{}".format(
                    info_df.price["zipeth"], info_df.price["zipusdt"],
                    info_df.price["ethusdt"]))
                time.sleep(second)
            else:
                lprint('差价太小,本次无法套利 方式一{} 方式二{}'.format(taoli1, taoli2),
                       logging.DEBUG)

        if time.time() - self.time_last_call > heartbeat_interval:
            self.time_last_call = time.time()
            thread1 = threading.Thread(target=self.fcoin.get_server_time)
            thread2 = threading.Thread(target=self.fcoin.get_server_time)
            thread3 = threading.Thread(target=self.fcoin.get_server_time)
            thread1.start()
            thread2.start()
            thread3.start()

    def run(self):
        self.symbols_action()
        # self.get_balance_action(symbols)
        balance.balance()
        self.client = fcoin_client(self.on_close)
        self.client.start()
        self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
        while True:
            tickers = ticker_queue.get()
            self.trade(tickers)
            ticker_queue.queue.clear()

    def on_close(self):
        print("websocket closed, try to restart...")
        time.sleep(second)
        self.client = fcoin_client(self.on_close)
        self.client.start()
        self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
Exemple #3
0
from fcoin import Fcoin
#if python3 use fcoin3
#from fcoin3 import Fcoin

fcoin = Fcoin()

print(fcoin.get_symbols())

print(fcoin.get_currencies())

fcoin.auth('you-key', 'you-secret')

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'))
Exemple #4
0
class ArbitrageRobot(object):
    """docstring for Robot"""
    def __init__(self):
        self.fcoin = Fcoin(api_key, api_secret)
        self.price_decimals = {}
        self.amount_decimals = {}
        self.tickers = {}
        self.time_last_call = time.time()

    # 截取指定小数位数
    def trunc(self, f, n):
        return round(f, n)
        # return math.floor(f*10**n)/10**n

    def ticker_handler(self, message):
        if 'ticker' in message:
            symbol = message['type'].split('.')[1]
            self.tickers[symbol] = message['ticker']
            ticker_queue.put(self.tickers, block=False)
            logging.debug("get ticker")
            # logging.info("ticker message: {}".format(message))
        else:
            logging.debug("ticker message: {}".format(message))

    def symbols_action(self):
        all_symbols = self.fcoin.get_symbols()
        for symbol in symbol_pairs:
            for info in all_symbols:
                if symbol == info['name']:
                    self.price_decimals[symbol] = int(info['price_decimal'])
                    self.amount_decimals[symbol] = int(info['amount_decimal'])
                    break
        logging.info("price_decimals: {}".format(self.price_decimals))
        logging.info("amount_decimals: {}".format(self.amount_decimals))

    # 买操作
    def buy_action(self, this_symbol, this_price, this_amount, type="limit"):
        # this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        buy_result = self.fcoin.buy(this_symbol, this_price, this_amount, type)
        buy_order_id = buy_result['data']
        if buy_order_id:
            logging.info("买单 {} 价格成功委托, 订单ID {}".format(
                this_price, buy_order_id))
        return buy_order_id

    # 卖操作
    def sell_action(self, this_symbol, this_price, this_amount, type="limit"):
        # this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        sell_result = self.fcoin.sell(this_symbol, this_price, this_amount,
                                      type)
        sell_order_id = sell_result['data']
        if sell_order_id:
            logging.info("卖单 {} 价格成功委托, 订单ID {}".format(
                this_price, sell_order_id))
        return sell_order_id

    def strategy(self, type, pricedf, amount):
        self.time_last_call = time.time()
        if type == 1:
            s1amount = amount / pricedf[sp1]

            thread1 = threading.Thread(target=self.sell_action,
                                       args=(sp1, pricedf[sp1], s1amount))
            thread2 = threading.Thread(target=self.buy_action,
                                       args=(sp2, pricedf[sp2], s1amount))
            thread3 = threading.Thread(target=self.sell_action,
                                       args=(sp3, pricedf[sp3], amount))
            thread1.start()
            thread2.start()
            thread3.start()
        elif type == 2:
            s1amount = amount / pricedf[sp1]

            thread1 = threading.Thread(target=self.buy_action,
                                       args=(sp1, pricedf[sp1], s1amount))
            thread2 = threading.Thread(target=self.sell_action,
                                       args=(sp2, pricedf[sp2], s1amount))
            thread3 = threading.Thread(target=self.buy_action,
                                       args=(sp3, pricedf[sp3], amount))
            thread1.start()
            thread2.start()
            thread3.start()

    def trade(self, tickers=None):
        """套利策略,寻找一个三元pair,看是不是满足套利规则。
    ETH/USDT, FI/ETH, FI/USDT
    ethusdt买一价 * fieth买一价 / fiusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程:usdt买fi,卖fi换回eth,卖eth换回usdt
    fiusdt买一价 / fieth卖一价 / ethusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程为:usdt买eth,eht买fi,卖fi换回usdt
    买一下标为2, 卖一下标为4"""
        # time.sleep(sleepsecond)
        amount = _s2amount

        self_tickers = tickers

        if len(self_tickers) == len(symbol_pairs):
            taoli1 = self_tickers[sp3][2] * \
             self_tickers[sp1][2] / self_tickers[sp2][4]
            taoli2 = self_tickers[sp2][2] / \
             self_tickers[sp1][4] / self_tickers[sp3][4]

            if taoli1 > difference:
                pricedf = {
                    sp3: self_tickers[sp3][2],
                    sp2: self_tickers[sp2][4],
                    sp1: self_tickers[sp1][2]
                }
                if is_use_amount:
                    if self_tickers[sp3][3] < halfs2 or self_tickers[sp2][
                            5] < halfs1 or self_tickers[sp1][3] < halfs1:
                        logging.debug('挂单量太小,本次无法套利 方式一')
                        return

                logging.info("满足套利条件1 套利值为{:.4}‰".format(taoli1 * 1000 - 1000))
                self.strategy(1, pricedf, amount)
                logging.info("{}卖价:{} {}买价:{} {}卖价:{}".format(
                    sp1, pricedf[sp1], sp2, pricedf[sp2], sp3, pricedf[sp3]))
                time.sleep(sleepsecond)
                print("满足套利条件1 套利值为{:.4}‰".format(taoli1 * 1000 - 1000))
            elif taoli2 > difference:
                pricedf = {
                    sp3: self_tickers[sp3][4],
                    sp2: self_tickers[sp2][2],
                    sp1: self_tickers[sp1][4]
                }
                if is_use_amount:
                    if self_tickers[sp3][5] < halfs2 or self_tickers[sp2][
                            3] < halfs1 or self_tickers[sp1][5] < halfs1:
                        logging.debug('挂单量太小,本次无法套利 方式二')
                        return

                logging.info("满足套利条件2 套利值比为{:.4}‰".format(taoli2 * 1000 -
                                                          1000))
                self.strategy(2, pricedf, amount)
                logging.info("{}买价:{} {}卖价:{} {}买价:{}".format(
                    sp1, pricedf[sp1], sp2, pricedf[sp2], sp3, pricedf[sp3]))
                time.sleep(sleepsecond)
                print("满足套利条件2 套利值比为{:.4}‰".format(taoli2 * 1000 - 1000))
            else:
                logging.debug('差价太小,本次无法套利 方式一{} 方式二{}'.format(taoli1, taoli2))
                print('差价太小,本次无法套利 方式一{} 方式二{}'.format(taoli1, taoli2))
        else:
            time.sleep(sleepsecond)
            return

        if time.time() - self.time_last_call > heartbeat_interval:
            self.time_last_call = time.time()
            thread1 = threading.Thread(target=self.fcoin.get_server_time)
            thread2 = threading.Thread(target=self.fcoin.get_server_time)
            thread3 = threading.Thread(target=self.fcoin.get_server_time)
            thread1.start()
            thread2.start()
            thread3.start()

    def run(self):
        self.symbols_action()
        # self.get_balance_action(symbols)
        balance.balance(symbols)
        self.client = fcoin_client(self.on_close)
        self.client.start()
        self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
        while True:
            tickers = ticker_queue.get()
            self.trade(tickers)
            ticker_queue.queue.clear()

    def on_close(self):
        print("websocket closed, try to restart...")
        time.sleep(sleepsecond)
        self.client = fcoin_client(self.on_close)
        self.client.start()
        self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
Exemple #5
0
class Robot(object):
	"""docstring for Robot"""
	def __init__(self):
		self.fcoin = Fcoin(api_key, api_secret)

	# 截取指定小数位数
	def trunc(self, f, n):
		return round(f, n)

	def ticker_handler(self, message):
		if 'ticker' in message:
			self.ticker = message['ticker']
		# print('ticker', self.ticker)

	def symbols_action(self):
		all_symbols = self.fcoin.get_symbols()
		for info in all_symbols:
			if symbol == info['name']:
				self.price_decimal = int(info['price_decimal'])
				self.amount_decimal = int(info['amount_decimal'])
				print('price_decimal:', self.price_decimal, 'amount_decimal:', self.amount_decimal)
				return

	# 查询账户余额
	def get_balance_action(self, symbols, specfic_symbol = None):
		balance_info = self.fcoin.get_balance()
		specfic_balance = 0
		for info in balance_info['data']:
			for symbol in symbols:
				if info['currency'] == symbol:
					balance = info
					print(balance['currency'], '账户余额', balance['balance'], '可用', balance['available'], '冻结', balance['frozen'])
					if info['currency'] == specfic_symbol:
						specfic_balance = float(info['available'])
		return specfic_balance

	# 买操作
	def buy_action(self, this_symbol, this_price, this_amount, should_repeat = 0):
		ticker = self.ticker
		print('准备买入', this_price, ticker)
		buy_result = self.fcoin.buy(this_symbol, self.trunc(this_price, self.price_decimal), this_amount)
		print('buy_result is', buy_result)
		buy_order_id = buy_result['data']
		if buy_order_id:
			print('买单', this_price, '价格成功委托', '订单ID', buy_order_id)
		return buy_order_id

	# 卖操作
	def sell_action(self, this_symbol, this_price, this_amount):
		ticker = self.ticker
		print('准备卖出', this_price, ticker)
		if is_direct_buy == 1:
			sell_result = self.fcoin.sell(this_symbol, self.trunc(this_price * (1 - 0.0002), self.price_decimal), this_amount)
		else:
			sell_result = self.fcoin.sell(this_symbol, this_price, this_amount)
		print('sell_result is: ', sell_result)
		sell_order_id = sell_result['data']
		if sell_order_id:
			print('卖单', this_price, '价格成功委托', '订单ID', sell_order_id)
		return sell_order_id


	def strategy(self, symbol, order_price, amount):
		print('使用单边震荡策略')
		buy_id = self.buy_action(symbol, order_price, amount)
		sell_id = self.sell_action(symbol, order_price, amount)

	def trade(self):
		time.sleep(second)
		print(bytes.decode(base64.b64decode(b'6LSt5Lmw6K+36K6k5YeG5b6u5L+h5Y+3YXJjaGVyemhz77yM5LiN6KaB55u45L+h5YW25LuW55qE5p2l5rqQ')))
		ticker = self.ticker
		newest_price = ticker[0]
		high_bids = ticker[2]
		high_bids_amount = ticker[3]
		low_ask = ticker[4]
		low_ask_amount = ticker[5]
		order_price = self.trunc((low_ask + high_bids) / 2, self.price_decimal)
		real_price_difference = float(low_ask - high_bids)
		print('最低卖价:', low_ask, '最高买价', high_bids, '欲下订单价: ', order_price, 
				'当前差价:', '{:.9f}'.format(real_price_difference), '设定差价:', '{:.9f}'.format(price_difference))
		if real_price_difference > price_difference:
			print('现在价格:', newest_price, '挂单价格', order_price)
			self.strategy(symbol, order_price, amount)
		else:
			print('差价太小,放弃本次成交')

	def run(self):
		self.client = fcoin_client()
		self.client.start()
		self.client.subscribe_ticker(symbol, self.ticker_handler)
		self.symbols_action()
		self.get_balance_action(symbols)
		while True:
			self.trade()
class Robot(object):
    logging.basicConfig(filename='logger.log', level=logging.WARN)
    """docstring for Robot"""
    def __init__(self):
        self.fcoin = Fcoin(api_key, api_secret)

    # 截取指定小数位数
    def trunc(self, f, n):
        return round(f, n)

    def ticker_handler(self, message):
        if 'ticker' in message:
            self.ticker = message['ticker']
        # print('ticker', self.ticker)

    def symbols_action(self):
        all_symbols = self.fcoin.get_symbols()
        for info in all_symbols:
            if symbol == info['name']:
                self.price_decimal = int(info['price_decimal'])
                self.amount_decimal = int(info['amount_decimal'])
                print('price_decimal:', self.price_decimal, 'amount_decimal:',
                      self.amount_decimal)
                return

    # 查询账户余额
    def get_balance_action(self, symbols, specfic_symbol=None):
        balance_info = self.fcoin.get_balance()
        specfic_balance = 0
        for info in balance_info['data']:
            for symbol in symbols:
                if info['currency'] == symbol:
                    balance = info
                    print(balance['currency'], '账户余额', balance['balance'],
                          '可用', balance['available'], '冻结', balance['frozen'])
                    if info['currency'] == specfic_symbol:
                        specfic_balance = float(info['available'])
        return specfic_balance

    # 买操作
    def buy_action(self,
                   this_symbol,
                   this_price,
                   this_amount,
                   diff,
                   should_repeat=0):
        ticker = self.ticker
        cur_price = str(self.trunc(this_price - diff, self.price_decimal))
        print('准备买入', this_price, ticker)
        buy_result = self.fcoin.buy(this_symbol, cur_price, str(this_amount))
        print('buy_result is', buy_result)
        buy_order_id = buy_result['data']
        if buy_order_id:
            print('++++++++++++++++++++++++++++买单: ' + cur_price +
                  '价格成功委托, 订单ID: ' + buy_order_id)
            logging.warning('买单: ' + cur_price + '价格成功委托, 订单ID: ' +
                            buy_order_id)
        return buy_order_id

    # 卖操作
    def sell_action(self, this_symbol, this_price, this_amount, diff):
        ticker = self.ticker
        cur_price = str(self.trunc(this_price + diff, self.price_decimal))
        print('准备卖出', cur_price, ticker)
        sell_result = self.fcoin.sell(this_symbol, cur_price, str(this_amount))
        print('sell_result is: ', sell_result)
        sell_order_id = sell_result['data']
        if sell_order_id:
            print('----------------------------卖单: ' + cur_price +
                  '价格成功委托, 订单ID: ' + sell_order_id)
            logging.warning('卖单: ' + cur_price + '价格成功委托, 订单ID: ' +
                            sell_order_id)
        return sell_order_id

    def list_active_orders(self, this_symbol, state='submitted'):
        dt = datetime(fees_start_time['year'], fees_start_time['month'],
                      fees_start_time['day'], fees_start_time['hour'],
                      fees_start_time['minute'], fees_start_time['second'])
        timestamp = int(dt.timestamp() * 1000)
        return self.fcoin.list_orders(symbol=this_symbol,
                                      states=state,
                                      after=timestamp)

    def get_order_count(self, this_symbol):
        order_list = self.list_active_orders(this_symbol)
        order_buy = 0
        order_sell = 0
        price_buy_max = 0
        price_buy_min = 655350
        id_buy_min = ""
        price_sell_min = 655350
        price_sell_max = 0
        id_sell_max = ""
        for i in range(len(order_list['data'])):
            price_cur = float(order_list['data'][i]['price'])
            if order_list['data'][i]['side'] == 'buy':
                order_buy = order_buy + 1
                if price_cur > price_buy_max:
                    price_buy_max = price_cur
                if price_cur < price_buy_min:
                    price_buy_min = price_cur
                    id_buy_min = order_list['data'][i]['id']
            else:
                order_sell = order_sell + 1
                if price_cur < price_sell_min:
                    price_sell_min = price_cur
                if price_cur > price_sell_max:
                    price_sell_max = price_cur
                    id_sell_max = order_list['data'][i]['id']
        order_price_range = abs(price_sell_max - price_buy_min)
        print("buy_count:", order_buy, "buy_min:", price_buy_min, "buy_max:",
              price_buy_max, "sell_count:", order_sell, "sell_min",
              price_sell_min, "sell_max", price_sell_max, "order_price_range",
              order_price_range)
        return (order_buy, price_buy_max, id_buy_min, order_sell,
                price_sell_min, id_sell_max, order_price_range)

    def adjust(self, real_diff, order_price):
        diff = order_price * price_diff
        if (diff < real_diff):
            diff = real_diff
        buy_diff = diff
        sell_diff = diff
        return (buy_diff, sell_diff)

    def strategy(self, symbol, order_price, amount, real_diff):
        order_buy, price_buy_max, id_buy_min, order_sell, price_sell_min, id_sell_max, order_price_range = self.get_order_count(
            symbol)
        if (order_price_range > trade_range):
            if (order_buy > order_sell + order_count_diff):
                if "" != id_buy_min:
                    print("order_price_range:", order_price_range,
                          "buy_order_cancel:", id_buy_min)
                    self.fcoin.cancel_order(id_buy_min)
            if (order_sell > order_buy + order_count_diff):
                if "" != id_sell_max:
                    print("order_price_range", order_price_range,
                          "sell_order_cancel:", id_sell_max)
                    self.fcoin.cancel_order(id_sell_max)

        buy_diff, sell_diff = self.adjust(real_diff, order_price)
        cur_price_range = price_range * order_price
        if ((price_buy_max + cur_price_range) < order_price):
            try:
                buy_id = self.buy_action(symbol, order_price, amount, buy_diff)
            except Exception as err:
                print("failed to buy", err)
        if ((price_sell_min - cur_price_range) > order_price):
            try:
                sell_id = self.sell_action(symbol, order_price, amount,
                                           sell_diff)
            except Exception as err:
                print("failed to sell", err)

    def trade(self):
        time.sleep(second)
        ticker = self.ticker
        newest_price = ticker[0]
        high_bids = ticker[2]
        high_bids_amount = ticker[3]
        low_ask = ticker[4]
        low_ask_amount = ticker[5]
        order_price = self.trunc((low_ask + high_bids) / 2, self.price_decimal)
        real_price_difference = float(low_ask - high_bids)
        print('最低卖价:', low_ask, '最高买价', high_bids, '欲下订单价: ', order_price,
              '当前差价:', '{:.9f}'.format(real_price_difference), '设定差价:',
              '{:.9f}'.format(price_difference))
        if real_price_difference > price_difference:
            print('现在价格:', newest_price, '挂单价格', order_price)
            self.strategy(symbol, order_price, amount,
                          real_price_difference / 2)
        else:
            print('差价太小,放弃本次成交')

    def run(self):
        self.client = fcoin_client()
        self.client.start()
        self.client.subscribe_ticker(symbol, self.ticker_handler)
        self.symbols_action()
        self.get_balance_action(symbols)

        time = 0
        while True:
            self.trade()
            time = time + 1
            if (time > 100):
                break
    cf.read("fcoin.conf")
    key = cf.get('api', 'key')
    secret = cf.get('api', 'secret')
    symbol = cf.get('brush', 'symbol')
    currency = cf.get('brush', 'currency')
    addr = cf.get('peer', 'addr')
    server_port = cf.get('peer', 'server_port')
    peer_port = cf.get('peer', 'peer_port')
    actor = cf.get('peer', 'actor')
except Exception:
    print('please check the config file <fcoin.conf> in parent direction')
    exit(1)

fcoin = Fcoin()
fcoin.auth(key, secret)
symbols = fcoin.get_symbols()
send_queue = Queue.Queue(maxsize=1)
recv_queue = Queue.Queue(maxsize=1)
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((addr, int(server_port)))

serial = 0


class Sender(threading.Thread):
    def run(self):
        while True:
            data_obj = send_queue.get()
            data = pickle.dumps(data_obj)
            udp_socket.sendto(data.encode('utf-8'), (addr, int(peer_port)))
            print('send data=%s to address=%s' % (str(data_obj), addr))
Exemple #8
0
class ArbitrageRobot(object):
    """docstring for Robot"""
    def __init__(self):
        self.fcoin = Fcoin(api_key, api_secret)
        self.price_decimals = {}
        self.amount_decimals = {}
        self.tickers = {}

    # 截取指定小数位数
    def trunc(self, f, n):
        # return round(f, n)
        return math.floor(f * 10**n) / 10**n

    def ticker_handler(self, message):
        # print(message)
        if 'ticker' in message:
            symbol = message['type'].split('.')[1]
            self.tickers[symbol] = message['ticker']
            logging.debug("ticker: {}".format(message['ticker']))
        else:
            logging.debug("ticker message: {}".format(message))

    def symbols_action(self):
        all_symbols = self.fcoin.get_symbols()
        for symbol in symbol_pairs:
            for info in all_symbols:
                if symbol == info['name']:
                    self.price_decimals[symbol] = int(info['price_decimal'])
                    self.amount_decimals[symbol] = int(info['amount_decimal'])
                    break
        logging.info("price_decimals: {}".format(self.price_decimals))

    # 买操作
    def buy_action(self,
                   this_symbol,
                   this_price,
                   this_amount,
                   should_repeat=0):
        this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        # ticker = self.tickers[this_symbol]
        # print('准备买入', this_price, ticker)
        buy_result = self.fcoin.buy(this_symbol, this_price, this_amount)
        # print('buy_result is', buy_result)
        buy_order_id = buy_result['data']
        if buy_order_id:
            lprint("买单 {} 价格成功委托, 订单ID {}".format(this_price, buy_order_id))
        return buy_order_id

    # 卖操作
    def sell_action(self, this_symbol, this_price, this_amount):
        this_price = self.trunc(this_price, self.price_decimals[this_symbol])
        this_amount = self.trunc(this_amount,
                                 self.amount_decimals[this_symbol])
        # ticker = self.tickers[this_symbol]
        # print('准备卖出', this_price, ticker)
        sell_result = self.fcoin.sell(this_symbol, this_price, this_amount)
        # print('sell_result is: ', sell_result)
        sell_order_id = sell_result['data']
        if sell_order_id:
            lprint("卖单 {} 价格成功委托, 订单ID {}".format(this_price, sell_order_id))
        return sell_order_id

    def strategy(self, type, pricedf, amount):
        print('使用套利策略')
        if type == 1:
            usdtamount = amount * pricedf["ethusdt"]
            ftamount = usdtamount / pricedf["ftusdt"]
            self.sell_action("fteth", pricedf["fteth"], ftamount)
            self.buy_action("ftusdt", pricedf["ftusdt"], ftamount)
            self.sell_action("ethusdt", pricedf["ethusdt"], amount)

        elif type == 2:
            ftamount = amount / pricedf["fteth"]
            self.buy_action("ethusdt", pricedf["ethusdt"], amount)
            self.sell_action("ftusdt", pricedf["ftusdt"], ftamount)
            self.buy_action("fteth", pricedf["fteth"], ftamount)

    def trade(self):
        """套利策略,寻找一个三元pair,看是不是满足套利规则。
    ETH/USDT, FT/ETH, FT/USDT
    ethusdt买一价 * fteth买一价 / ftusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程:usdt买ft,卖ft换回eth,卖eth换回usdt
    ftusdt买一价 / fteth卖一价 / ethusdt卖一价, 如果大于1很多,就存在套利空间
    操作流程为:usdt买eth,eht买ft,卖ft换回usdt
    买一下标为2, 卖一下标为4"""
        time.sleep(second)

        if len(self.tickers) == len(symbol_pairs):
            info_df = pd.DataFrame(self.tickers).T
            # 买一卖一的均价
            info_df["price"] = (info_df[2] + info_df[4]) / 2
            taoli1 = info_df.price["ethusdt"] * \
             info_df.price["fteth"] / info_df.price["ftusdt"]
            taoli2 = info_df.price["ftusdt"] / \
             info_df.price["fteth"] / info_df.price["ethusdt"]
            # print(taoli1, taoli2)
            # 从eth开始交易
            if taoli1 > difference:
                self.strategy(1, info_df.price, ethamount)
                lprint("满足套利条件1 套利值为{:.4}‰".format(taoli1 * 1000 - 1000))
                lprint("ethusdt卖价:{} ftusdt买价:{} fteth卖价:{}".format(
                    info_df.price["ethusdt"], info_df.price["ftusdt"],
                    info_df.price["fteth"]))
            elif taoli2 > difference:
                self.strategy(2, info_df.price, ethamount)
                lprint("满足套利条件2 套利值比为{:.4}‰".format(taoli2 * 1000 - 1000))
                lprint("fteth买价:{} ftusdt卖价:{} ethusdt买价:{}".format(
                    info_df.price["fteth"], info_df.price["ftusdt"],
                    info_df.price["ethusdt"]))
            else:
                lprint('差价太小,本次无法套利 方式一{} 方式二{}'.format(taoli1, taoli2),
                       logging.DEBUG)

    def run(self):
        self.client = fcoin_client()
        self.client.start()
        self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
        self.symbols_action()
        # self.get_balance_action(symbols)
        balance.balance()
        while True:
            self.trade()
Exemple #9
0
class Robot(object):
    """docstring for Robot"""
    def __init__(self):
        self.fcoin = Fcoin(api_key, api_secret)

        # self.ticker = []
        self.time_since_last_call = 0

    # 截取指定小数位数
    def trunc(self, f, n):
        # return round(f, n)
        return math.floor(f * 10**n) / 10**n

    def ticker_handler(self, message):
        if 'ticker' in message:
            self.ticker = message['ticker']
        # print('ticker', self.ticker)

    def symbols_action(self):
        all_symbols = self.fcoin.get_symbols()
        for info in all_symbols:
            if symbol == info['name']:
                self.price_decimal = int(info['price_decimal'])
                self.amount_decimal = int(info['amount_decimal'])
                # print('price_decimal:', self.price_decimal, 'amount_decimal:', self.amount_decimal)
                return

    # 查询账户余额
    def get_balance_action(self, symbols, specfic_symbol=None):
        balance_info = self.fcoin.get_balance()
        specfic_balance = 0
        for info in balance_info['data']:
            for symbol in symbols:
                if info['currency'] == symbol:
                    balance = info
                    print(balance['currency'], '账户余额', balance['balance'],
                          '可用', balance['available'], '冻结', balance['frozen'])
                    if info['currency'] == specfic_symbol:
                        specfic_balance = float(info['available'])
        return specfic_balance

    # 买操作
    def buy_action(self,
                   this_symbol,
                   this_price,
                   this_amount,
                   should_repeat=0):
        # ticker = self.ticker
        # print('准备买入', this_price, ticker)
        buy_result = self.fcoin.buy(this_symbol,
                                    self.trunc(this_price, self.price_decimal),
                                    this_amount)
        # print('buy_result is', buy_result)
        buy_order_id = buy_result['data']
        if buy_order_id:
            lprint('买单{} 价格成功委托 订单ID{}'.format(this_price, buy_order_id))
        return buy_order_id

    # 卖操作
    def sell_action(self, this_symbol, this_price, this_amount):
        # ticker = self.ticker
        # print('准备卖出', this_price, ticker)
        sell_result = self.fcoin.sell(this_symbol, this_price, this_amount)
        # print('sell_result is: ', sell_result)
        sell_order_id = sell_result['data']
        if sell_order_id:
            lprint('卖单{} 价格成功委托 订单ID{}'.format(this_price, sell_order_id))
        return sell_order_id

    def strategy(self, symbol, order_price, amount, gap):
        # print('使用单边震荡策略')
        # lprint("start strategy", logging.DEBUG)
        buy_price = self.trunc(order_price - gap, self.price_decimal)
        sell_price = self.trunc(order_price + gap, self.price_decimal)
        if is_multi_thread:
            buy_thread = threading.Thread(target=self.buy_action,
                                          args=(symbol, buy_price, amount))
            sell_thread = threading.Thread(target=self.sell_action,
                                           args=(symbol, sell_price, amount))
            buy_thread.start()
            sell_thread.start()
        else:
            self.buy_action(symbol, buy_price, amount)
            self.sell_action(symbol, sell_price, amount)

    def trade(self):
        time.sleep(second)
        ticker = self.ticker
        # if len(ticker) == 0:
        # return
        # newest_price = ticker[0]
        high_bids = ticker[2]
        high_bids_amount = ticker[3]
        low_ask = ticker[4]
        low_ask_amount = ticker[5]
        order_price = (low_ask + high_bids) / 2
        real_price_difference = float(low_ask - high_bids)
        if real_price_difference > price_difference:
            gap = 0
            if is_mutable_gap:
                gap = real_price_difference / 3
            elif is_using_gap:
                gap = price_difference / 3
            # print('现在价格:', newest_price, '挂单价格', order_price)

            lprint('最低卖价: {} 最高买价: {} 当前差价:{:.9f} 买卖差价: {:.9f}'.format(
                low_ask, high_bids, real_price_difference, gap * 2))
            if is_mutable_amount:
                trade_amount = min(high_bids_amount, low_ask_amount) / 2
                if trade_amount > maxamount:
                    trade_amount = maxamount
                if trade_amount < miniamount:
                    trade_amount = miniamount
                trade_amount = self.trunc(trade_amount, self.amount_decimal)
                self.strategy(symbol, order_price, trade_amount, gap)
            else:
                self.strategy(symbol, order_price, amount, gap)

            self.time_since_last_call = 0
        else:
            print('最低卖价: {} 最高买价: {} 当前差价:{:.9f} 设定差价: {:.9f}'.format(
                low_ask, high_bids, real_price_difference, price_difference))
            print('差价太小,放弃本次成交')
            self.time_since_last_call += second
            if self.time_since_last_call > heartbeat_interval:
                # inorder to keep-alive
                if is_multi_thread:
                    buy_thread = threading.Thread(
                        target=self.fcoin.get_server_time)
                    sell_thread = threading.Thread(
                        target=self.fcoin.get_server_time)
                    buy_thread.start()
                    sell_thread.start()
                else:
                    self.fcoin.get_server_time()
                self.time_since_last_call = 0

    def run(self):
        self.client = fcoin_client(self.on_close)
        # self.client = fcoin_client()
        self.client.start()
        self.client.subscribe_tickers([symbol], self.ticker_handler)
        self.symbols_action()
        # self.get_balance_action(symbols)
        if not is_mutable_amount:
            logging.info("交易标的:{} 每单交易量:{} {}".format(symbol, amount,
                                                      symbols[0]))
        balance.balance()
        while True:
            self.trade()

    def on_close(self):
        print("websocket closed, try to restart...")
        time.sleep(second)
        # self.client = fcoin_client(self.on_close)
        self.client.start()
        self.client.subscribe_tickers([symbol], self.ticker_handler)
from fcoin import Fcoin
#if python3 use fcoin3
#from fcoin3 import Fcoin


fcoin = Fcoin()

print(fcoin.get_symbols())

print(fcoin.get_currencies())

fcoin.auth('you-key', 'you-secret') 

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'))