def getBalance(): """ 返回 btc/usdt/ft的持仓信息 :return: """ public_balance_deal = Fcoin() public_balance_deal.auth(accessKey, secretyKey) result, data = public_balance_deal.get_balance() btc_num = 0 usdt_num = 0 ft_num = 0 if str(data["status"]) == "0": for info in data["data"]: currency = info["currency"].lower() if currency == "btc": btc_num = float(info["balance"]) if currency == "usdt": usdt_num = float(info["balance"]) if currency == "ft": ft_num = float(info["balance"]) return btc_num, usdt_num, ft_num else: return btc_num, usdt_num, ft_num
def __init__(self): self.client = fcoin_client() self.client.stream.stream_depth.subscribe(self.depth) self.client.stream.stream_klines.subscribe(self.candle) self.client.stream.stream_ticker.subscribe(self.ticker) self.fcoin = Fcoin() self.fcoin.auth(config.key, config.secret) self.buy_price = None # 买1价 self.buy_amount = None # 买1量 self.sell_price = None # 卖1价 self.sell_amount = None # 卖1量 self.ts = None # 深度更新时间 self.market_price = None # 市价 self.total_bids = 0 self.total_asks = 0 self.filled_buy_order_list = [] self.order_list = defaultdict(lambda: None) self.buy_order_id = None self.dic_balance = defaultdict(lambda: None) self.time_order = time.time() self.price_list = [] self.candle_list = None self.SMA = None self._init_log()
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 __init__(self): self.client = FcoinClient() self.fcoin = Fcoin() self.fcoin.auth(config.key, config.secret) self._sender = MqSender('fcoin', 'kline') self.sym = '' self.wdata = {} self._init_log()
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 __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 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
def test_create_order(repeat=10): # 估算时间差 system_delta = test_network() lprint('预计系统时间差:{:.4}ms'.format(system_delta)) fcoin = Fcoin(api_key, api_secret) beginat = time.time() symbol = "fteth" # price = fcoin.get_market_price(symbol) price = 0.00001 logging.info('begin create order test: buy {}'.format(symbol)) orders_info = [] for i in range(repeat): old = int(time.time()*1000) buy_result = fcoin.buy(symbol, price, 3) now = int(time.time()*1000) lprint("before:{} after:{} delta:{}ms".format(old, now, now-old)) logging.debug("buy order result:{}".format(buy_result)) orders_info.append((buy_result['data'], old)) endat = time.time() lprint('total time:{:.5}s avg time:{:.4}ms'.format( endat-beginat, (endat-beginat)/repeat*1000)) # 计算从下单开始,到系统记录下单之间的时间 delta_times = [] for order_id, call_time in orders_info: order = fcoin.get_order(order_id) delta = int(order['data']['created_at']) - call_time # cancel the test order fcoin.cancel_order(order_id) delta_times.append(delta) avg = sum(delta_times)/len(delta_times) lprint('average time delta: {:.5}ms differece:{:.4}ms'.format( avg, system_delta)) lprint('平均下单时间为:{:.4}ms'.format(avg+system_delta))
from fcoin import Fcoin #if python3 use fcoin3 #from fcoin3 import Fcoin fcoin = Fcoin() print(fcoin.get_symbols()) print(fcoin.get_currencies()) fcoin.auth('key', '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'))
def cancelAll(): print("cancelAll") sleep(1.5) cancel_order_nums = 3 public_order_deal = Fcoin() public_order_deal.auth(accessKey, secretyKey) all_orders = [] for state in ["submitted", "partial_filled"]: result, data = public_order_deal.list_orders(symbol="btcusdt", states=state) if str(data["status"]) == "0": orders = data["data"] for use_order in orders: all_orders.append(use_order) sleep(2) if len(all_orders) > 0: buy_order_array = [] sell_order_array = [] for use_order in all_orders: systemID = str(use_order["id"]) status = use_order["state"] tradedVolume = float(use_order["filled_amount"]) totalVolume = float(use_order["amount"]) price = float(use_order["price"]) side = use_order["side"] if status in ["partial_filled", "submitted", "partial_canceled"]: if side == "buy": buy_order_array.append([price, systemID]) else: sell_order_array.append([price, systemID]) all_need_cancel = [] if len(buy_order_array) > cancel_order_nums: sort_buy_arr = sorted(buy_order_array, key=lambda price_pair: price_pair[0]) sort_buy_arr.reverse() print('sort_buy_arr :{}'.format(sort_buy_arr)) for i in range(cancel_order_nums, len(sort_buy_arr)): all_need_cancel.append(str(sort_buy_arr[i][1])) # public_order_deal.cancel_order( str(sort_buy_arr[i][1])) if len(sell_order_array) > cancel_order_nums: sort_sell_arr = sorted(sell_order_array, key=lambda price_pair: price_pair[0]) print(u'sort_sell_arr'.format(sort_sell_arr)) for i in range(cancel_order_nums, len(sell_order_array)): all_need_cancel.append(str(sort_sell_arr[i][1])) for systemID in all_need_cancel: try: print(public_order_deal.cancel_order(systemID)) sleep(1.5) except Exception as ex: print(ex, file=sys.stderr) else: print("order_all is not ")
sarr = str(f).split('.') if len(sarr) == 2: s1, s2 = str(f).split('.') else: s1 = str(f) s2 = '0' if n == 0: return s1 if n <= len(s2): return s1 + '.' + s2[:n] return s1 + '.' + s2 + '0' * (n - len(s2)) currency = {'ft':'usdt','btc':'usdt','eth':'usdt','bch':'usdt','ltc':'usdt','etc':'usdt','btm':'usdt','zip':'eth','icx':'eth','omg':'eth','zil':'eth'} fcoin = Fcoin() fcoin.auth('key', 'secret') #try: # balances balance = fcoin.get_balance()['data'] balances = [bal for bal in balance if bal['balance'] != '0.000000000000000000'] if balances: sum_usdt = 0 for bal in balances: if bal['currency'] != 'usdt': tickername = bal['currency']+currency[bal['currency']] ticker = fcoin.get_market_ticker(tickername)['data']['ticker']
def runBuy(accessKey, secretyKey, price, volume): fcoin = Fcoin() fcoin.auth(accessKey, secretyKey) return fcoin.buy('btcusdt', price, volume)
def runSell(accessKey, secretyKey, price, volume): fcoin = Fcoin() fcoin.auth(accessKey, secretyKey) return fcoin.sell('btcusdt', price, volume)
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'))
def __init__(self): self.fcoin = Fcoin(api_key, api_secret)
# -*- coding: utf-8 -*- # !/usr/bin/env python import logging import os from config import kline_interval import time from fcoin import Fcoin import config import mmap from config import sdb, mdb fcoin = Fcoin() fcoin.auth(config.key, config.secret) sDir = os.path.join(os.path.abspath('..'), config.sD) class BaseSync(object): def __init__(self, platform, data_type, interval=''): self.data_type = data_type self.platform = platform self.interval = interval # self._init_log() def run(self, *args): self.client.start() while not self.client.isConnected: self._log.info('waitting……') time.sleep(0.5) self.sync_data(*args) while True:
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)
import logging import os from config import kline_interval from config import exchange from config import restapi from enums import Platform from enums import Symbol from fcoin import Fcoin from config import time_spot from config import dateFormat import csv import time import json fcoin = Fcoin() fcoin.auth('key ', 'secret') datadir = '/yanjiuyuan/data' if os.environ.get("SHELL", "") else os.path.join(os.path.abspath('..'), 'data') class BaseSync(object): def __init__(self, platform, data_type): self.data_type = data_type self.platform = platform def run(self, *args): try: self.sync_data(*args) except Exception as error: print(error)
from fcoin import Fcoin #if python3 use fcoin3 #from fcoin3 import Fcoin fcoin = Fcoin() print(fcoin.get_symbols()) print(fcoin.get_currencies()) fcoin.auth('', '') 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'))
class MarketApp: """ """ def __init__(self): self.client = FcoinClient() self.fcoin = Fcoin() self.fcoin.auth(config.key, config.secret) self._sender = MqSender('fcoin', 'kline') self.sym = '' self.wdata = {} self._init_log() # self.deleteFromMmap(sfilepath, size-iseekpos,size) def deleteFromMmap(self, filename, start, end, lastline=False): self.sym = self.sym # acutally it will not be used just for fix the warnning error f = open(filename, "r+") VDATA = mmap.mmap(f.fileno(), 0) size = len(VDATA) if lastline is True: start = size - start end = size else: pass length = end - start newsize = size - length VDATA.move(start, end, size - end) VDATA.flush() VDATA.close() f.truncate(newsize) f.close() def candle(self, data): # print('数据:', data) name, ml, sym = self.client.channel_config[0].split('.') ts = int(round(data['id'] * 1000)) # self.client.get_ts() # send to mq try: mqdata = {} tdata = { 'symbol': sym, 'ts': ts, 'tm_intv': m_interval, 'exchange': config.exchange } mqdata.update(tdata) mqdata.update(data) # print(mqdata) self._sender.send(str(mqdata)) except Exception as error: print(error) self._sender.close() # send to mq # print('symbol: ', sym) # create the no-exist folder to save date stime = time.strftime('%Y%m%d', time.localtime()) stradeDir = os.path.join(sDir, stime, config.exchange, config.klinedir) if not os.path.exists(stradeDir): os.makedirs(stradeDir) # for original data sTfile = '{0}_{1}_{2}{3}'.format(config.klinedir, stime, sym, '.txt') sTfilepath = os.path.join(stradeDir, sTfile) # write original data to txt files with open(sTfilepath, 'a+', encoding='utf-8') as tf: tf.writelines(json.dumps(data) + '\n') # for no-duplicated csv data sfile = '{0}_{1}_{2}{3}'.format(config.klinedir, stime, sym, '.csv') sfilepath = os.path.join(stradeDir, sfile) if self.wdata: if ts in self.wdata.values(): # self.wdata['ts'] = ts pass else: self.wdata['ts'] = ts self.wdata['wlen'] = 0 # write the current data sent from server to the csv but the position will be changed else: self.wdata['ts'] = ts self.wdata['wlen'] = 0 self.w2csv(sfilepath, ts, sym, data) def w2csv(self, sfilepath, ts, sym, data): sflag = 'close' rFind = False kklist = [] vvlist = [] # will delete the data from the end if the ts is the same to the previous data iseekpos = self.wdata['wlen'] # print('iseekpos= '+'{0}'.format(iseekpos)) if iseekpos > 0: # print('will call deleteFromMmap') self.deleteFromMmap(sfilepath, iseekpos, 0, True) # will delete the data from the end if the ts is the same to the one of the previous data else: pass 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(data.values()) self.additem2list(ts, vvlist, sym, m_interval, vlist) w.writerow(vvlist) else: # khead = ['symbol', 'ts', 'tm_intv', 'id', 'open', 'close', 'low', 'high', 'amount', 'vol', 'count'] klist = list(data.keys()) # open,close,high,quote_vol,id,count,low,seq,base_vol kklist.insert(0, 'symbol') kklist.insert(1, 'ts') kklist.insert(2, 'tm_intv') kklist.insert(3, klist[4]) kklist.insert(4, klist[0]) kklist.insert(5, klist[1]) kklist.insert(6, klist[6]) kklist.insert(7, klist[2]) kklist.insert(8, 'amount') kklist.insert(9, 'vol') kklist.insert(10, klist[5]) w.writerow(kklist) vlist = list(data.values()) self.additem2list(ts, vvlist, sym, m_interval, vlist) w.writerow(vvlist) # update the lenth of data wroten to csv prelen = len('{0},{1},{2}'.format(sym, ts, m_interval)) # print('prelen= ' + '{0}'.format(prelen)) for i in dkey: ss = '{0}{1}'.format(',', data[i]) prelen += len(ss) prelen += len( '\t\n') # because there is a extra '\t\n' which is equal 2 bytes # print('w2csv prelen= ' + '{0}'.format(prelen)) self.wdata['wlen'] = prelen # print('w2csv after prelen= ' + '{0}'.format(self.wdata['wlen'])) # update the lenth of data wroten to csv # add extral items to the original list def additem2list(self, ts, vvlist, sym, ml, vlist): self.sym = sym # acutally it will not be used just for fix the warnning error vvlist.insert(0, sym) vvlist.insert(1, ts) vvlist.insert(2, ml) vvlist.insert(3, vlist[4]) vvlist.insert(4, vlist[0]) vvlist.insert(5, vlist[1]) vvlist.insert(6, vlist[6]) vvlist.insert(7, vlist[2]) vvlist.insert(8, vlist[3]) vvlist.insert(9, vlist[8]) vvlist.insert(10, vlist[5]) # 循环 def loop(self): self.client.start() while not self.client.isConnected: self._log.info('waitting……') time.sleep(1) self.sync_kline(self.sym) while True: try: pass except Exception as error: print(error) time.sleep(1) # sync_trades def sync_kline(self, sym): self.client.stream.stream_klines.subscribe(self.candle) self.client.subscribe_candle(sym, config.mflag) # 日志初始化 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 fteth(self, profit_margin, volumn_rate): fcoin = Fcoin() #print(fcoin.get_symbols()) fcoin.auth(key, secret) balance = (fcoin.get_balance())['data'] for i in balance: if i['currency'] == u'eth': #print i eth_balance = i['balance'] eth_available = i['available'] if eth_balance != eth_available: print('Warning: Some ETH frozen: ', i) sys.exit(0) for i in balance: if i['currency'] == u'ft': #print i ft_balance = i['balance'] ft_available = i['available'] if ft_available != ft_balance: print('Warning: Some FT frozen: ', i) sys.exit(0) result = (fcoin.get_market_ticker(u'fteth')) #result=(fcoin.get_currencies()) #print(result) #print(result['status']) #print(result['data']['ticker']) _latest_trans_price = result['data']['ticker'][0] _latest_volumn = result['data']['ticker'][1] _max_buy_price = result['data']['ticker'][2] _max_buy_volumn = result['data']['ticker'][3] _min_sell_price = result['data']['ticker'][4] _min_sell_volumn = result['data']['ticker'][5] #buy_price = _latest_trans_price*0.92 buy_price = _latest_trans_price * 1.0 buy_price = round(buy_price, 8) ## keep 8 decimal can_buy_ft = int(float(eth_available) / buy_price) buy_volumn = int(float(can_buy_ft) * float(volumn_rate)) result = fcoin.buy('fteth', buy_price, buy_volumn) sell_price = buy_price * (1.0 + profit_margin) sell_price = round(sell_price, 8) ## keep 8 decimal sell_volumn = buy_volumn # sell all print('ticker fteth latest price:', _latest_trans_price) print("order_price = ", buy_price, "order_volumn = ", buy_volumn) print("sell_price = ", sell_price) #print result buy_id = result['data'] buy_order_done = 0 sell_order_done = 0 #buy_id_decode = base64.b64decode(bytes(buy_id)) print buy_id #print buy_id_decode buy_cycle_time = 3 ## wait 5 seconds * 3 times = 15 seconds sell_cycle_time = 180 ## wait 10 seconds * 180 times = 30 mins while (buy_cycle_time > 0): time.sleep(5) result = fcoin.get_order(buy_id) #result = fcoin.show_orders('fteth') #print result filled = result['data']['filled_amount'] #print int(filled) if int(float(filled)) == buy_volumn: print('buy order done !') buy_order_done = 1 break buy_cycle_time = buy_cycle_time - 1 if buy_cycle_time == 0: print 'Timeout!! Buy price is too low, please try again' print 'Cancel buy order!' fcoin.cancel_order(buy_id) if buy_order_done == 1: result = fcoin.sell('fteth', sell_price, sell_volumn) sell_id = result['data'] while (sell_cycle_time > 0): time.sleep(20) result = fcoin.get_order(sell_id) #print result filled = result['data']['filled_amount'] if int(float(filled)) == sell_volumn: print('sell order done !') sell_order_done = 1 break sell_cycle_time = sell_cycle_time - 1 if sell_cycle_time % 5 == 0: print 'Sell price is too high, cancel order,try again' fcoin.cancel_order(sell_id) time.sleep(1) sell_price = sell_price * 0.999 ## price down 0.001 sell_price = round(sell_price, 8) ## keep 8 decimal sell_volumn = sell_volumn - int(float(filled)) result = fcoin.sell('fteth', sell_price, sell_volumn) sell_id = result['data'] print('sell_price = ', sell_price) print('sell_volumn = ', sell_volumn)
class wss_app(): def __init__(self): self.client = fcoin_client() self.client.stream.stream_depth.subscribe(self.depth) self.client.stream.stream_klines.subscribe(self.candle) self.client.stream.stream_ticker.subscribe(self.ticker) self.fcoin = Fcoin() self.fcoin.auth(config.key, config.secret) self.buy_price = None # 买1价 self.buy_amount = None # 买1量 self.sell_price = None # 卖1价 self.sell_amount = None # 卖1量 self.ts = None # 深度更新时间 self.market_price = None # 市价 self.total_bids = 0 self.total_asks = 0 self.filled_buy_order_list = [] self.order_list = defaultdict(lambda: None) self.buy_order_id = None self.dic_balance = defaultdict(lambda: None) self.time_order = time.time() self.price_list = [] self.candle_list = None self.SMA = None 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 digits(self, num, digit): site = pow(10, digit) tmp = num * site tmp = math.floor(tmp) / site return tmp # wss订阅深度接收 def depth(self, data): bids = data['bids'] asks = data['asks'] self.ts = time.time() self.buy_price = bids[0] # 买 self.buy_amount = bids[1] self.sell_price = asks[0] # 卖 self.sell_amount = asks[1] for i in range(3): self.total_bids += bids[2 * i - 1] self.total_asks += asks[2 * i - 1] # wss订阅K线接收 def candle(self, data): if self.candle_list is None: self.candle_list = [{ 'timestamp': data['id'], 'open': data['open'], 'high': data['high'], 'low': data['low'], 'close': data['close'], 'volume': data['base_vol'] }] else: last_candle = self.candle_list[-1] if last_candle['timestamp'] == data['id']: self.candle_list[-1] = { 'timestamp': data['id'], 'open': data['open'], 'high': data['high'], 'low': data['low'], 'close': data['close'], 'volume': data['base_vol'] } else: self.candle_list.append({ 'timestamp': data['id'], 'open': data['open'], 'high': data['high'], 'low': data['low'], 'close': data['close'], 'volume': data['base_vol'] }) if len(self.candle_list) > 10: self.candle_list.pop(0) if len(self.candle_list) >= 7: close_array = np.array( [item['close'] for item in self.candle_list]) self.SMA = talib.SMA(close_array, timeperiod=7) # 市价 def ticker(self, data): self.ts = time.time() self.market_price = data['ticker'][0] # 刷单流程 def process(self): if self.ts and time.time( ) - self.ts < 10 and self.buy_price and self.market_price: price = self.market_price if config.fix_price == 0 else config.fix_price amount = 0 ''' 挂卖单 ''' success_item_list = [] for item in self.filled_buy_order_list: amount = self.digits(item['amount'], config.symbol['amount_precision']) price = self.digits(max(item['price'], price), config.symbol['price_precision']) order = [amount, price] if amount >= config.symbol['min_amount']: success, data = self.fcoin.sell(config.symbol['name'], price, amount) # 卖 if success: success_item_list.append(item) self.order_list[data['data']] = order self._log.info('挂卖单成功[%s:%s]' % (amount, price)) ''' 删除已成功订单 ''' for item in success_item_list: self.filled_buy_order_list.remove(item) keys = [] for key in self.order_list.keys(): success, data = self.fcoin.get_order(key) if success: state = data['data']['state'] if state == 'filled': keys.append([0, key]) elif state in ('partial_canceled', 'canceled'): keys.append([1, key]) for tag, key in keys: self.order_list.pop(key) if tag == 0: self._log.info('已经成交:' + key) else: self._log.info('已经撤单:' + key) ''' 买单不存在时 ''' if not self.buy_order_id: ''' 价格异动识别,可以根据实际情况改动,价格固定时无效 ''' if config.fix_price == 0: if abs(self.buy_price - self.sell_price) > 0.5: self._log.info('价格异动买卖差价:%s' % abs(self.buy_price - self.sell_price)) return elif self.SMA is None: if len(self.price_list) > 0: avg = sum(self.price_list) / len(self.price_list) if abs(avg - self.buy_price) > 10: self._log.info('价格异动avg:%s [%s]' % (avg, self.buy_price)) self.price_list.append(self.buy_price) self.price_list.append(self.sell_price) if len(self.price_list) >= 120: self.price_list.pop(0) return else: self.price_list.append(self.buy_price) self.price_list.append(self.sell_price) else: last = self.SMA[-2] if not np.isnan(last): if abs(self.buy_price - last) >= 0.5: self._log.info('价格异动:%s' % abs(self.buy_price - last)) return ''' 查询余额度 ''' self.dic_balance = self.get_balance() ''' 判断币种持仓量,到设定值停止买入。 ''' coin = self.dic_balance[config.symbol['coin']] if coin and coin.balance > config.limit_amount: self._log.info('%s余额度达到最大值[%s]' % (config.symbol['coin'], coin.balance)) return ''' 挂买单 ''' usdt = self.dic_balance['usdt'] if usdt: if config.fix_price: diff = abs(config.fix_price - self.market_price) if config.diff_price < diff: self._log.info('固定价格模式差价异常[%-0.2f]' % diff) return price = self.market_price if config.fix_price == 0 else config.fix_price if usdt.available > price * config.max_amount: amount = config.max_amount if self.total_bids > config.total_amount and self.total_asks > config.total_amount else config.min_amount else: amount = usdt.available / price amount = self.digits(amount, config.symbol['amount_precision']) if amount >= config.symbol['min_amount']: price = self.digits(price, config.symbol['price_precision']) success, data = self.fcoin.buy(config.symbol['name'], 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('usdt不足[%s]' % (usdt.available)) else: self._log.info('查询余额错误') else: ''' 买单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.filled_buy_order_list.append({ 'price': price, 'amount': amount }) if state == 'filled': self.buy_order_id = None self._log.info('买单已成交') elif state == 'canceled' or state == 'partial_canceled': self.buy_order_id = None self._log.info('买单已撤单') elif state not in ('pending_cancel'): ''' 超时判断 ''' if time.time() - self.time_order >= config.delay: self.fcoin.cancel_order(self.buy_order_id) self._log.info('%s秒超时撤单' % config.delay) else: self._log.info('等待WebSocket数据……') # 循环 def loop(self): if config.min_amount < config.symbol[ 'min_amount'] or config.min_amount < config.symbol[ 'min_amount']: self._log.info('max_amount,min_amount ≥ 规定的最小数量[%s]' % (config.symbol['min_amount'])) return self.client.start() while not self.client.isConnected: self._log.info('waitting……') time.sleep(1) self.client.subscribe_depth(config.symbol['name'], 'L20') self.client.subscribe_candle(config.symbol['name'], 'M1') self.client.subscribe_ticker(config.symbol['name']) while True: try: self.process() except Exception as error: self._log.info('未知错误') time.sleep(0.5) # 获取余额 def get_balance(self): dic_balance = defaultdict(lambda: None) success, data = self.fcoin.get_balance() if success: for item in data['data']: dic_balance[item['currency']] = balance( float(item['available']), float(item['frozen']), float(item['balance'])) return dic_balance # 获取订单 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 __init__(self): self.fcoin = Fcoin(api_key, api_secret) self.price_decimals = {} self.amount_decimals = {} self.tickers = {} self.time_last_call = time.time()
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)
from fcoin import Fcoin fcoin = Fcoin() fcoin.auth('6b709e792d484932a06298e0f408692b', '8fc3e8dc802548788f2c55287c16d021') balance = fcoin.get_balance() FT_USDT_QTY = 10 FT_ETH_QTY = 10 ETH_USDT_QTY = 10 ''' balance_ft = 0 balance_usdt = 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)) '''
class wss_app: def __init__(self): self.client = fcoin_client() self.client.stream.stream_depth.subscribe(self.depth) self.client.stream.stream_klines.subscribe(self.candle) self.client.stream.stream_ticker.subscribe(self.ticker) self.fcoin = Fcoin() self.fcoin.auth(config.key, config.secret) self.buy_price = None # 买1价 self.buy_amount = None # 买1量 self.sell_price = None # 卖1价 self.sell_amount = None # 卖1量 self.ts = None # 深度更新时间 self.market_price = None # 市价 self.total_bids = 0 self.total_asks = 0 self.filled_buy_order_list = [] self.order_list = defaultdict(lambda: None) self.buy_order_id = None self.dic_balance = defaultdict(lambda: None) self.time_order = time.time() self.price_list = [] self.candle_list = None self.SMA = None 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 digits(self, num, digit): site = pow(10, digit) tmp = num * site tmp = math.floor(tmp) / site return tmp # wss订阅深度接收 def depth(self, data): bids = data["bids"] asks = data["asks"] self.ts = time.time() self.buy_price = bids[0] # 买 self.buy_amount = bids[1] self.sell_price = asks[0] # 卖 self.sell_amount = asks[1] for i in range(3): self.total_bids += bids[2 * i - 1] self.total_asks += asks[2 * i - 1] # wss订阅K线接收 def candle(self, data): if self.candle_list is None: self.candle_list = [ { "timestamp": data["id"], "open": data["open"], "high": data["high"], "low": data["low"], "close": data["close"], "volume": data["base_vol"], } ] else: last_candle = self.candle_list[-1] if last_candle["timestamp"] == data["id"]: self.candle_list[-1] = { "timestamp": data["id"], "open": data["open"], "high": data["high"], "low": data["low"], "close": data["close"], "volume": data["base_vol"], } else: self.candle_list.append( { "timestamp": data["id"], "open": data["open"], "high": data["high"], "low": data["low"], "close": data["close"], "volume": data["base_vol"], } ) if len(self.candle_list) > 10: self.candle_list.pop(0) if len(self.candle_list) >= 7: close_array = np.array([item["close"] for item in self.candle_list]) self.SMA = talib.SMA(close_array, timeperiod=7) # 市价 def ticker(self, data): self.ts = time.time() self.market_price = data["ticker"][0] # 刷单流程 def process(self): if ( self.ts and time.time() - self.ts < 10 and self.buy_price and self.market_price ): price = self.market_price if config.fix_price == 0 else config.fix_price amount = 0 """ 挂卖单 """ success_item_list = [] for item in self.filled_buy_order_list: amount = self.digits(item["amount"], config.symbol["amount_precision"]) price = self.digits( max(item["price"], price), config.symbol["price_precision"] ) order = [amount, price] if amount >= config.symbol["min_amount"]: success, data = self.fcoin.sell( config.symbol["name"], price, amount ) # 卖 if success: success_item_list.append(item) self.order_list[data["data"]] = order self._log.info("挂卖单成功[%s:%s]" % (amount, price)) """ 删除已成功订单 """ for item in success_item_list: self.filled_buy_order_list.remove(item) keys = [] for key in self.order_list.keys(): success, data = self.fcoin.get_order(key) if success: state = data["data"]["state"] if state == "filled": keys.append([0, key]) elif state in ("partial_canceled", "canceled"): keys.append([1, key]) for tag, key in keys: self.order_list.pop(key) if tag == 0: self._log.info("已经成交:" + key) else: self._log.info("已经撤单:" + key) """ 买单不存在时 """ if not self.buy_order_id: """ 价格异动识别,可以根据实际情况改动,价格固定时无效 """ if config.fix_price == 0: if abs(self.buy_price - self.sell_price) > 0.5: self._log.info( "价格异动买卖差价:%s" % abs(self.buy_price - self.sell_price) ) return elif self.SMA is None: if len(self.price_list) > 0: avg = sum(self.price_list) / len(self.price_list) if abs(avg - self.buy_price) > 10: self._log.info( "价格异动avg:%s [%s]" % (avg, self.buy_price) ) self.price_list.append(self.buy_price) self.price_list.append(self.sell_price) if len(self.price_list) >= 120: self.price_list.pop(0) return else: self.price_list.append(self.buy_price) self.price_list.append(self.sell_price) else: last = self.SMA[-2] if not np.isnan(last): if abs(self.buy_price - last) >= 0.5: self._log.info("价格异动:%s" % abs(self.buy_price - last)) return """ 查询余额度 """ self.dic_balance = self.get_balance() """ 判断币种持仓量,到设定值停止买入。 """ coin = self.dic_balance[config.symbol["coin"]] if coin and coin.balance > config.limit_amount: self._log.info( "%s余额度达到最大值[%s]" % (config.symbol["coin"], coin.balance) ) return """ 挂买单 """ usdt = self.dic_balance["usdt"] if usdt: if config.fix_price: diff = abs(config.fix_price - self.market_price) if config.diff_price < diff: self._log.info("固定价格模式差价异常[%-0.2f]" % diff) return price = ( self.market_price if config.fix_price == 0 else config.fix_price ) if usdt.available > price * config.max_amount: amount = ( config.max_amount if self.total_bids > config.total_amount and self.total_asks > config.total_amount else config.min_amount ) else: amount = usdt.available / price amount = self.digits(amount, config.symbol["amount_precision"]) if amount >= config.symbol["min_amount"]: price = self.digits(price, config.symbol["price_precision"]) success, data = self.fcoin.buy( config.symbol["name"], 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("usdt不足[%s]" % (usdt.available)) else: self._log.info("查询余额错误") else: """ 买单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.filled_buy_order_list.append( {"price": price, "amount": amount} ) if state == "filled": self.buy_order_id = None self._log.info("买单已成交") elif state == "canceled" or state == "partial_canceled": self.buy_order_id = None self._log.info("买单已撤单") elif state not in ("pending_cancel"): """ 超时判断 """ if time.time() - self.time_order >= config.delay: self.fcoin.cancel_order(self.buy_order_id) self._log.info("%s秒超时撤单" % config.delay) else: self._log.info("等待WebSocket数据……") # 循环 def loop(self): if ( config.min_amount < config.symbol["min_amount"] or config.min_amount < config.symbol["min_amount"] ): self._log.info( "max_amount,min_amount ≥ 规定的最小数量[%s]" % (config.symbol["min_amount"]) ) return self.client.start() while not self.client.isConnected: self._log.info("waitting……") time.sleep(1) self.client.subscribe_depth(config.symbol["name"], "L20") self.client.subscribe_candle(config.symbol["name"], "M1") self.client.subscribe_ticker(config.symbol["name"]) while True: try: self.process() except Exception as error: self._log.info("未知错误") time.sleep(0.5) # 获取余额 def get_balance(self): dic_balance = defaultdict(lambda: None) success, data = self.fcoin.get_balance() if success: for item in data["data"]: dic_balance[item["currency"]] = balance( float(item["available"]), float(item["frozen"]), float(item["balance"]), ) return dic_balance # 获取订单 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
# # -*- coding: utf-8 -*- """ """ import pandas as pd from fcoin import Fcoin import os,csv,time fcoin = Fcoin() fcoin.auth('key ', 'secret') sylist = ['btcusdt','ethusdt','bchusdt','ltcusdt','ftusdt','fteth','etcusdt','ftbtc','bnbusdt','btmusdt','zrxeth'] sDir = os.path.join(os.path.abspath('..'),'..','Fcoin_DL','KLine') stime = time.strftime('%Y-%m-%d',time.localtime()) # 获取最新的深度明细 # 买(卖)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)
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 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)
from fcoin import Fcoin from buy import Buy import datetime import schedule import time fcoin = Fcoin() fcoin.auth('', '') coin_buy = Buy('ftusdt', fcoin=fcoin, type='limit') def buyTask(): print("I'm working for buy and sell") coin_buy.buy() def run(): schedule.every(1).seconds.do(buyTask) while True: schedule.run_pending() if __name__ == '__main__': run()
# -*- coding=utf-8 -*- # @Author: zz # @Date: 2018-06-24 18:15:55 # @Last Modified by: zhiz # @Last Modified time: 2018-06-25 13:24:31 from fcoin import Fcoin from auth import api_key, api_secret from config import symbol_type # 初始化 fcoin = Fcoin(api_key, api_secret) # 查询账户余额 def get_balance_action(symbols): balance_info = fcoin.get_balance() print(balance_info) 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']) def balance(): # 账户余额 get_balance_action(symbol_type) # 守护进程 if __name__ == '__main__': balance()