def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] self.RecordPools = [] for k, v in enumerate(self.markets): market = v['id'] dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t
def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = Mood() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); self.zuorizhangting = {} self.datas = []
def __init__(self, period, path): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets f = open(path, 'r') r = csv.DictReader(f) self.markets = [] for row in r: id = row['code'] self.markets.append({'id': id}) # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] print 'markt count ', len(self.markets) for k, v in enumerate(self.markets): market = v['id'] self.exchange.refresh(self.period, market) dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t
def __init__(self, period, markets): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets if markets == None: self.markets = self.exchange.getMarkets() else: self.markets = markets # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = TrutleAverage() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t
class FixApplication(fix.Application): exchange = Exchange() def onCreate(self, sessionID): return def onLogon(self, sessionID): print("New session logon '%s'." % sessionID.toString()) self.exchange.market_publisher.broadcast(self.exchange.lob.publish()) return def onLogout(self, sessionID): return def toAdmin(self, sessionID, message): return def fromAdmin(self, sessionID, message): return def toApp(self, message, sessionID): print("Sending [%s]: %s" % (sessionID, message.toString())) return def fromApp(self, message: fix.Message, sessionID): msgType = fix.MsgType() message.getHeader().getField(msgType) type = msgType.getValue() if type == fix.MsgType_NewOrderSingle: self.on_new_order_single(message, sessionID) elif type == fix.MsgType_OrderCancelRequest: self.on_order_cancel_request(message, sessionID) elif type == fix.MsgType_OrderCancelReplaceRequest: self.on_order_cancel_replace_request(message, sessionID) else: return fix.UnsupportedMessageType def on_new_order_single(self, message: fix.Message, session_id: fix.SessionID): ordType = fix.OrdType() message.getField(ordType) if ordType.getValue() != fix.OrdType_LIMIT: raise fix.IncorrectTagValue(ordType.getField()) symbol = fix.Symbol() message.getField(symbol) side = fix.Side() message.getField(side) orderQty = fix.OrderQty() message.getField(orderQty) price = fix.Price() message.getField(price) clOrdID = fix.ClOrdID() message.getField(clOrdID) client_id = fix.ClientID() message.getField(client_id) if ordType.getValue() == fix.OrdType_LIMIT: so = SessionOrder( session_id, LimitOrder( self.exchange.gen_order_id(), client_id.getValue(), symbol.getValue(), Side.BID if (side.getValue() == fix.Side_BUY) else Side.ASK, orderQty.getValue(), price.getValue())) else: so = SessionOrder( session_id, MarketOrder( self.exchange.gen_order_id(), client_id.getValue(), symbol.getValue(), Side.BID if (side.getValue() == fix.Side_BUY) else Side.ASK, orderQty.getValue())) so.order.ClOrdID = int(clOrdID.getValue()) ack_order, trades = self.exchange.create_order(so) # Execution Reports self.send_order_status(ack_order) if len(trades) > 0: self.send_trade_reports(trades) def on_order_cancel_request(self, message: fix.Message, session_id: fix.SessionID): clOrdID = fix.ClOrdID() message.getField(clOrdID) self.exchange.cancel_order(session_id.toString(), int(clOrdID.getValue())) def on_order_cancel_replace_request(self, message: fix.Message, session_id: fix.SessionID): return NotImplementedError # REPORTING ###############################t######################################################################## execId = 0 def gen_exec_id(self) -> str: self.execId = self.execId + 1 return str(self.execId) def create_execution_report(self, so: SessionOrder, exec_type: fix.ExecType): report = fix.Message() report.getHeader().setField(fix.MsgType(fix.MsgType_ExecutionReport)) report.setField(fix.OrderID(str(so.order.id))) report.setField(fix.ClOrdID(str(so.order.ClOrdID))) report.setField(fix.ClientID(so.order.client_id)) report.setField(fix.ExecID(self.gen_exec_id())) report.setField(fix.ExecType(exec_type)) report.setField( fix.OrdStatus(order_status_to_fix(so.order.order_state))) report.setField(fix.LeavesQty(so.order.remaining)) report.setField(fix.CumQty(so.order.qty - so.order.remaining)) report.setField(fix.AvgPx(0)) report.setField(fix.Symbol(so.order.symbol)) report.setField(fix.Side(side_to_fix(so.order.side))) report.setField(fix.OrderQty(so.order.qty)) report.setField(fix.Price(so.order.price)) return report def send_trade_reports(self, trades: List[Trade]): def send_trade_report(so: SessionOrder, price, qty): report = self.create_execution_report(so, fix.ExecType_FILL) report.setField(fix.LastPx(price)) report.setField(fix.LastQty(qty)) fix.Session.sendToTarget(report, so.session_id) for t in trades: print(t) send_trade_report(t.buyer, t.price, t.qty) send_trade_report(t.seller, t.price, t.qty) def send_order_status(self, so: SessionOrder): report = self.create_execution_report(so, fix.ExecType_ORDER_STATUS) fix.Session.sendToTarget(report, so.session_id)
class TrutleStatB2C(): def __init__(self, period, path): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets f = open(path, 'r') r = csv.DictReader(f) self.markets = [] for row in r: id = row['code'] self.markets.append({'id': id}) # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] print 'markt count ', len(self.markets) for k, v in enumerate(self.markets): market = v['id'] self.exchange.refresh(self.period, market) dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); def Run(self): # print '-----------------------------------------------------------------' stop = False rest = True Pool = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) if len(dk) == 0: continue ret = r.Run(dk, self.period, self.currenttimestamp) if ret != None: ret['market'] = market if ret['result'] == 2: Pool.append(ret) if len(dk) > 0: rest = False Pool.sort(key=lambda v: v['vol_rate'], reverse=False) if rest == False: self.Pool = Pool if len(Pool) > 0: print "message", time.strftime( '%Y-%m-%d', time.localtime(self.currenttimestamp)) print '\t', Pool if self.currenttimestamp > time.time(): stop = True return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow(['code']) for k, v in enumerate(self.Pool): d = [] d.append(v['market']) w.writerow(d) f.close()
class TrutleStatAverage(): def __init__(self, period, markets): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets if markets == None: self.markets = self.exchange.getMarkets() else: self.markets = markets # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = TrutleAverage() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); def Run(self): # print '-----------------------------------------------------------------' stop = False rest = True Pool = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) ret = r.Run(dk, self.period, self.currenttimestamp) if ret != None: ret['market'] = market if ret['result'] == 1: Pool.append(ret) if len(dk) > 0: rest = False Pool.sort(key=lambda v: v['rate'], reverse=True) print Pool if self.currenttimestamp > time.time(): stop = True if rest == False: self.Pool = Pool print len(Pool), time.strftime( '%Y-%m-%d', time.localtime(self.currenttimestamp)) return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow(['code']) for k, v in enumerate(self.Pool): d = [] d.append(v['market']) w.writerow(d) f.close()
from tvizbase.api import Api #Загрузка настроек из файла path = os.path.dirname(__file__) if path == '': path = '.' with open(path + '/settings.json', 'r') as sett_file: settings = json.load(sett_file) decimal.getcontext().rounding = 'ROUND_HALF_UP' #Подключение к базе redis redis = redis.Redis(db=settings['redis_db']) #Подключение к БЧ VIZ viz = Api() #Создание класса обменника exchange = Exchange(settings, viz=viz, redis=redis) #Получение номера последнего обработанного блока try: last_block_num = int(redis.get('viz_last_block_num')) except: exchange.send_alert('Ошибка чтения из базы данных. Скрипт остановлен.') sys.exit('Ошибка чтения из базы данных. Скрипт остановлен.') #Публикация настроек из файла в блокчейн exchange.post_status() exchange.post_new_rate(exchange.viz_balance, exchange.usdt_balance) #Получение и обработка новых блоков каждые 3 секунды one_minute = three_minute = datetime.timestamp(datetime.now()) while (True): block_num = viz.get_dynamic_global_properties()['head_block_number'] while (last_block_num < block_num): last_block_num += 1
class Statis2(): def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = Mood2() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); self.zuorizhangting = {} self.datas = [] def run(self): # print '-----------------------------------------------------------------' stop = False rest = True # markets nmarkets = self.exchange.getMarkets() if nmarkets: self.markets = nmarkets data = {} stats = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) ret = r.Run(dk, self.period, self.currenttimestamp) if ret != None: ret['market'] = market stats.append(ret) if len(dk) > 0: rest = False if rest: print 'rest', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) sucessRatio = 0 avgIncrease1 = 0 minIncrease1 = 100 maxIncrease1 = 0 avgIncrease2 = 0 minIncrease2 = 100 maxIncrease2 = 0 avgIncrease3 = 0 minIncrease3 = 100 maxIncrease3 = 0 jinrizhangting = {} for k, v in enumerate(stats): sucessRatio = sucessRatio + v["success"] avgIncrease1 = avgIncrease1 + v["increase_1"] avgIncrease2 = avgIncrease2 + v["increase_2"] avgIncrease3 = avgIncrease3 + v["increase_3"] minIncrease1 = min(minIncrease1, v["increase_1"]) minIncrease2 = min(minIncrease2, v["increase_2"]) minIncrease3 = min(minIncrease3, v["increase_3"]) maxIncrease1 = max(maxIncrease1, v["increase_1"]) maxIncrease3 = max(maxIncrease2, v["increase_2"]) maxIncrease2 = max(maxIncrease3, v["increase_3"]) sc = len(stats) data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) data["count"] = sc if sc > 0: data['sucessRatio'] = round(sucessRatio / (float)(sc), 2) data["avgIncrease1"] = round(avgIncrease1 / sc, 2) data["avgIncrease2"] = round(avgIncrease2 / sc, 2) data["avgIncrease3"] = round(avgIncrease3 / sc, 2) else: data['sucessRatio'] = 0 data["avgIncrease1"] = 0 data["avgIncrease2"] = 0 data["avgIncrease3"] = 0 minIncrease1 = 0 minIncrease2 = 0 minIncrease3 = 0 data["minIncrease1"] = minIncrease1 data["minIncrease2"] = minIncrease2 data["minIncrease3"] = minIncrease3 data["maxIncrease1"] = maxIncrease1 data["maxIncrease2"] = maxIncrease2 data["maxIncrease3"] = maxIncrease3 if not rest and sc > 0: self.datas.append(data) if self.currenttimestamp > time.time(): stop = True return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'time', 'count', 'sucessRatio', 'avgIncrease1', 'minIncrease1', 'maxIncrease1', 'avgIncrease2', 'minIncrease2', 'maxIncrease2', 'avgIncrease3', 'minIncrease3', 'maxIncrease3' ]) for k, data in enumerate(self.datas): d = [] d.append(data['time']) d.append(data['count']) d.append(data['sucessRatio']) d.append(data['avgIncrease1']) d.append(data['minIncrease1']) d.append(data['maxIncrease1']) d.append(data['avgIncrease2']) d.append(data['minIncrease2']) d.append(data['maxIncrease2']) d.append(data['avgIncrease3']) d.append(data['minIncrease3']) d.append(data['maxIncrease3']) w.writerow(d) f.close()
s = '{:.9f}'.format(num); pos = s.find('.'); if pos > 0: print pos, s[0:pos+c+1], c, 'xxx', s,num; return float(s[0:pos+c+1]); else: return num; print cut(0.299, 2) print cut(299, 2) print cut(0.299, 5) print cut(1.234567890,4); print cut(0.0000012345,4); print (time.time()-time.time()+1 )/(60*5), time.time() #''' exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) exchange.delegate(huobiEX()); exchange.prepare(None, None) market='eosusdt'; ret1 = exchange.doOrder(market, 'sell', '30', 0.9980); print ret1; ret2 = exchange.doOrderCancel(ret1['data'], market); print ret2; ret3 = exchange.doOrder(market, 'sell', '30', 0.9980); print ret3; ret4 = exchange.doOrderCancel(ret3['data'], market); print ret4 #''' ''' x = [311, 308.5, 304.11, 305.50, 304.51, 308.86, 305.96, 306.07, 308.1, 308.6, 310.99]; y = [];
def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # user. self.user = User() info = self.exchange.getUser() print info # print '-----------------------------------' self.user.updatePositions(info['accounts']) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. # for k, v in enumerate(self.markets): market = v['id'] # order. # done in right env. self.user.updateOrder(self.exchange.getOrder(market)) # k line. if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = WVStats() # r = MutliMovingAverage(); r.Run(dk) lastk = r.KLines.Get(-1) if lastk: currency = market #market[0:len(market)-3]; self.user.updateHigh(currency, lastk.c) # c or high self.user.updateCost(currency, lastk.c) self.rules[market] = r Log.d( 'index:%d, start market:%s, begin time %s, current time:%s' % (k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))) #scale. self.scales = []
class Rebot(): def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # user. self.user = User() info = self.exchange.getUser() print info # print '-----------------------------------' self.user.updatePositions(info['accounts']) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. # for k, v in enumerate(self.markets): market = v['id'] # order. # done in right env. self.user.updateOrder(self.exchange.getOrder(market)) # k line. if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = WVStats() # r = MutliMovingAverage(); r.Run(dk) lastk = r.KLines.Get(-1) if lastk: currency = market #market[0:len(market)-3]; self.user.updateHigh(currency, lastk.c) # c or high self.user.updateCost(currency, lastk.c) self.rules[market] = r Log.d( 'index:%d, start market:%s, begin time %s, current time:%s' % (k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))) #scale. self.scales = [] def run(self): #print '-----------------------------------------------------------------' # markets nmarkets = self.exchange.getMarkets() if nmarkets: self.markets = nmarkets # user info = self.exchange.getUser() self.user.updatePositions(info['accounts']) if RebotConfig.rebot_release: print 'positions:' for k, v in (self.user.positions.items()): if v['volume'] * v['high'] > 10: print '\t{0} {1}'.format(k, v) # print '\n' sv = self.user.positions[RebotConfig.base_currency]['volume'] flag = False stop = True buylist = [] selllist = [] for k, v in enumerate(self.markets): market = v['id'] # order. # done in right env. orders = self.user.updateOrder(self.exchange.getOrder(market)) # rule r = self.rules[market] lastk = r.KLines.Get(-1) prelastk = lastk # k line. # dk = self.exchange.getK(market, 500, self.period, lastk.t); # print 'do market : %s' % market; dk = None type = None if lastk: kcount = 2 if RebotConfig.rebot_is_test == False: kcount = int( math.floor((time.time() - lastk.t) / (self.period * 60)) + 2) if kcount < 2: kcount = 2 dk = self.exchange.getK(market, kcount, self.period, lastk.t) #print dk if dk and len(dk) > 0: ret = r.Run(dk) lastk = r.KLines.Get(-1) type = ret.get('type') if RebotConfig.rebot_release: print market, time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)), time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(time.time())), lastk for orderkey, o in enumerate(orders): if o.checkMustCancel(): Log.d('\tcancel olded order {0}'.format(o)) if (self.exchange.doOrderCancel(o.id, market) and o.type == 'sell'): time.sleep(1) try: self.exchange.doOrder(market, 'sell', lastk.c, o.leftvolume) except Exception as e: Log.d('\trepeat order failed! e:%s' % e) # print '\tmarket status : {1}, last k time : {2}, type : {3}'.format(market, r.status, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)), type); if lastk and prelastk and lastk.t != prelastk.t: stop = False currency = market[0:len(market) - len(RebotConfig.base_currency)] pc = self.user.positions.get(currency) if pc and lastk: current = pc['volume'] * lastk.c sv += current self.user.updateHigh(currency, lastk.c) # c or high cost = self.user.getCost(currency) if cost and cost > 0 and False: scale = (current - cost) / cost * 100 rate = RebotConfig.rebot_loss_ratio if scale < rate: if RebotConfig.rebot_is_test: prate = (1 + rate * 1.1 / 100) nprateprice = pc['price'] * prate vol = self.user.doOrder(market, 'sell', nprateprice) print '\tmarket:%s, do sell, price:%f scale less %f, volume:%f, price:%f, time:%s' % ( market, pc['price'], rate, vol, nprateprice, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t))) scaleless = True self.exchange.doOrder(market, 'sell', nprateprice, vol, lastk.t) cost = self.user.getHighCost(currency) if False and cost and cost > 0 and scaleless == False: scale = (current - cost) / cost * 100 rate = RebotConfig.rebot_profit_ratio if scale < rate: if RebotConfig.rebot_is_test: prate = (1 + rate * 1.1 / 100) nprateprice = pc['high'] * prate vol = self.user.doOrder(market, 'sell', nprateprice) print '\tmarket:%s, do sell, high:%f scale less %f, volume:%f, high:%f, time:%s' % ( market, pc['high'], rate, vol, nprateprice, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t))) scaleless = True self.exchange.doOrder(market, 'sell', nprateprice, vol, lastk.t) if type == 'buy': buylist.append({'market': market, 'result': ret}) if type == 'sell': selllist.append({'market': market, 'result': ret}) # print 'do orders:' # sell nselllist = [] for key, v in enumerate(selllist): market = v['market'] nselllist.append(v) for key, v in enumerate(nselllist): market = v['market'] k = v['result']['k'] vol = self.user.doOrder(market, 'sell', k.c) if vol and vol > 0: flag = True orderresult, price, vol = self.exchange.doOrder( market, 'sell', k.c, vol, k.t, v['result']['ext']) r = self.rules[market] r.OrderResult(v['result'], orderresult) Log.d( '\tmarket:{0}, do:{1}, result:{2}, price:{3}, volume:{4}, time:{5}, ext:{6}' .format( market, 'SELL', orderresult, price, vol, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), v['result']['ext'])) #else: # print '\tmarket:%s, not enough to sell' % market; # buy nbuylist = [] for key, v in enumerate(buylist): market = v['market'] sort = v['result']['sort'] v['sort'] = sort angle = v['result'].get('angle') k = v['result']['k'] # print '\tmarket %s sort %f, angle %f, time %s' % (market, sort, angle, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))); if sort > 100 or sort < 0: print '\tmarket %s sort illegal, sort %f, time %s' % ( market, sort, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))) continue if angle and angle < RebotConfig.rebot_buy_least_angle: print '\tmarket %s angle illegal, angle %f, time %s' % ( market, angle, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))) continue nbuylist.append(v) # nbuylist.append(v); nbuylist.sort(key=lambda v: v['sort'], reverse=False) for key, v in enumerate(nbuylist): market = v['market'] k = v['result']['k'] vol = self.user.doOrder(market, 'buy', k.c) if vol and vol > 0: flag = True orderresult, price, vol = self.exchange.doOrder( market, 'buy', k.c, vol, k.t, v['result']['ext']) Log.d( '\tmarket:{0}, do:{1}, result:{2}, price:{3}, volume:{4}, time:{5}, ext:{6}' .format( market, 'BUY', orderresult, price, vol, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), v['result']['ext'])) else: print '\tnot enough cny !!! market:{0}, do:{1}, price:{2}, volume:{3}, time:{4}'.format( market, 'buy', k.c, vol, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))) #else: # print '\t!!! market:{0}, time:{1}, buy fail less volume : {2}'.format(market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(cwave.ck.t)), v['rmbvolumeN3']); if flag: ascale = (sv - self.user.initamount) / self.user.initamount * 100 self.scales.append(ascale) Log.d('all scale:{0}, current cny:{1}\n'.format(ascale, sv)) return stop
class Statis(): def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = Mood() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); self.zuorizhangting = {} self.datas = [] def run(self): # print '-----------------------------------------------------------------' stop = False rest = True # markets nmarkets = self.exchange.getMarkets() if nmarkets: self.markets = nmarkets data = {} stats = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) ret = r.Run(dk, self.period, self.currenttimestamp) ret['market'] = market stats.append(ret) if len(dk) > 0: rest = False if rest: print 'rest', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) statsconut = { "-3": 0, "-2": 0, "-1": 0, "0": 0, "1": 0, "2": 0, "3": 0 } maxlimitcount = 0 maxlimitmarket = 'None' limit2openincrese = 0 limit2count = 0 limit2increase = 0 jinrizhangting = {} for k, v in enumerate(stats): c = v["stat"] limit_count = v['limit_count'] market = v['market'] statsconut[str(c)] += 1 if self.zuorizhangting.get(market): limit2openincrese += v['open_increase'] limit2increase += v['increase'] if c > 0: limit2count += 1 if limit_count > 0: jinrizhangting[market] = True if maxlimitcount < limit_count: maxlimitcount = limit_count maxlimitmarket = market data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) data['ping'] = statsconut['0'] data[ "shangzhang"] = statsconut['3'] + statsconut['2'] + statsconut['1'] data['xiadie'] = statsconut['-3'] + statsconut['-2'] + statsconut['-1'] data['shangzhanglv'] = float( data["shangzhang"]) / float(data["shangzhang"] + data['xiadie'] + statsconut['0']) data["zhangting"] = statsconut["3"] data["kaiban"] = statsconut['2'] data['dieting'] = statsconut['-3'] data['lianbanshu'] = maxlimitcount data['maxlimitmarket'] = maxlimitmarket if statsconut['2'] + statsconut['3'] > 0: data['fengbanlv'] = float( statsconut['3']) / float(statsconut['2'] + statsconut['3']) else: data['fengbanlv'] = 1 if statsconut['-3'] > 0: data['zhangdietingbi'] = float(statsconut['3']) / float( statsconut['-3']) else: data['zhangdietingbi'] = 1 lenzuorizhangting = len(self.zuorizhangting) if lenzuorizhangting > 0: data[ 'y_lianbankaipanavg'] = limit2openincrese / lenzuorizhangting / 0.1 data['y_lianbanavg'] = limit2increase / lenzuorizhangting / 0.1 data['y_shangzhanglv'] = float(limit2count) / float( lenzuorizhangting) else: data['y_lianbankaipanavg'] = 0 data['y_lianbanavg'] = 0 data['y_shangzhanglv'] = 0 # print data; if rest == False: self.datas.append(data) self.zuorizhangting = jinrizhangting if self.currenttimestamp > time.time(): stop = True return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'time', 'ping', 'shangzhang', 'xiadie', 'shangzhanglv', 'zhangting', 'kaiban', 'dieting', 'fengbanlv', 'zhangdietingbi', 'lianbanshu', 'maxlimitmarket', 'y_lianbankaipanavg', "y_lianbanavg", "y_shangzhanglv" ]) for k, data in enumerate(self.datas): d = [] d.append(data['time']) d.append(data['ping']) d.append(data['shangzhang']) d.append(data['xiadie']) d.append(data['shangzhanglv']) d.append(data['zhangting']) d.append(data['kaiban']) d.append(data['dieting']) d.append(data['fengbanlv']) d.append(data['zhangdietingbi']) d.append(data['lianbanshu']) d.append(data['maxlimitmarket']) d.append(data['y_lianbankaipanavg']) d.append(data['y_lianbanavg']) d.append(data['y_shangzhanglv']) w.writerow(d) f.close()
#Библиотека для работы с БЧ VIZ from tvizbase.api import Api #Загрузка настроек из файла path = os.path.dirname(__file__) if path == '': path = '.' with open(path + '/settings.json', 'r') as sett_file: settings = json.load(sett_file) #Подключение к базе redis redis = redis.Redis(db=settings['redis_db']) #Подключение к БЧ VIZ viz = Api() #Создание класса обменника exchange = Exchange(settings, viz=viz, redis=redis) #Проверка наличия команды от бота try: tgbot_command = redis.get('tgbot_command').decode('utf-8') except: sys.exit() redis.delete('tgbot_command') #Старт или остановка обменника if tgbot_command == 'start': os.system(settings['exchange_start_cmd']) exchange.send_alert('Обменник запущен.') elif tgbot_command == 'stop': os.system(settings['exchange_stop_cmd']) exchange.send_alert('Обменник остановлен.')
class TrutleStatA2C(): def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] self.RecordPools = [] for k, v in enumerate(self.markets): market = v['id'] dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); def Run(self): # print '-----------------------------------------------------------------' stop = False rest = True Pool = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) if len(dk) == 0: continue ret = r.Run(dk, self.period, self.currenttimestamp) if ret != None: ret['market'] = market if ret['result'] == 2: Pool.append(ret) if len(dk) > 0: rest = False Log.d(time.strftime('%Y-%m-%d', time.localtime(self.currenttimestamp))) Pool.sort(key=lambda v: v['vol_rate'], reverse=False) if rest == False: poolsLen = len(self.RecordPools) for k in range(-5, 0): if abs(k) >= poolsLen: break rp = self.RecordPools[k] pl = rp['Pool'] Profits = rp['Profits'] ll = 0 hh = 0 avergp = 0 sratio = 0 if len(pl) > 0: cc = 0 for k1, v in enumerate(pl): r = self.rules[v['market']] kk = r.KLines[-1 + k] inc = round((r.KLines[-1].c - kk.c) / kk.c * 100, 2) hh = max(hh, inc) ll = min(ll, inc) avergp += inc if inc > 0: cc += 1 sratio = round(cc / (float)(len(pl)) * 100, 2) avergp = round(avergp / len(pl), 2) Profits.append({ ('avergp%d' % k): avergp, 'sratio%d' % k: sratio, 'hh%d' % k: hh, 'll%d' % k: ll }) self.RecordPools.append({ 'time': time.strftime('%Y-%m-%d', time.localtime(self.currenttimestamp)), 'Pool': Pool, 'Profits': [] }) self.Pool = Pool if len(Pool) > 0: #print "message", time.strftime('%Y-%m-%d', time.localtime(self.currenttimestamp)); mks = [] for k, v in enumerate(self.Pool): mks.append(v['market']) Log.d(mks) #print '\t', Pool; if self.currenttimestamp > time.time(): stop = True return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'time', 'avergp1', 'sratio1', 'hh1', 'll1', 'avergp2', 'sratio2', 'hh2', 'll2', 'avergp3', 'sratio3', 'hh3', 'll3', 'avergp4', 'sratio4', 'hh4', 'll4', 'avergp5', 'sratio5', 'hh5', 'll5' ]) for k, v in enumerate(self.RecordPools): d = [] d.append(v['time']) Profits = v['Profits'] print Profits if len(Profits) > 0: for i in range(1, len(Profits) + 1): pv = Profits[i - 1] if pv.has_key('avergp-%s' % i): d.append(Profits[i - 1]['avergp-%s' % i]) d.append(Profits[i - 1]['sratio-%s' % i]) d.append(Profits[i - 1]['hh-%s' % i]) d.append(Profits[i - 1]['ll-%s' % i]) else: d.append('0') d.append('0') d.append('0') w.writerow(d) f.close()
class TrutleStat(): def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 self.datas = [] for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 1, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); def run(self): # print '-----------------------------------------------------------------' stop = False rest = True # markets nmarkets = self.exchange.getMarkets() if nmarkets: self.markets = nmarkets data = {} PoolB = [] PoolC = [] self.currenttimestamp = self.exchange.getNextKTime( self.period, self.currenttimestamp) for k, v in enumerate(self.markets): market = v['id'] r = self.rules[market] dk = self.exchange.getK(market, 1, self.period, self.currenttimestamp) ret = r.Run(dk, self.period, self.currenttimestamp) if ret != None: ret['market'] = market if ret['result'] == 1: PoolB.append(ret) if ret['result'] == 2: PoolC.append(ret) if len(dk) > 0: rest = False # if rest : # print 'rest', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) if rest == False and len(PoolC) > 0: print 'Order Msg : ', time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(self.currenttimestamp)) for k, v in enumerate(PoolC): print v['market'] if self.currenttimestamp > time.time(): stop = True return stop def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'time', 'count', 'sucessRatio', 'avgIncrease1', 'minIncrease1', 'maxIncrease1', 'avgIncrease2', 'minIncrease2', 'maxIncrease2', 'avgIncrease3', 'minIncrease3', 'maxIncrease3' ]) for k, data in enumerate(self.datas): d = [] d.append(data['time']) d.append(data['count']) d.append(data['sucessRatio']) d.append(data['avgIncrease1']) d.append(data['minIncrease1']) d.append(data['maxIncrease1']) d.append(data['avgIncrease2']) d.append(data['minIncrease2']) d.append(data['maxIncrease2']) d.append(data['avgIncrease3']) d.append(data['minIncrease3']) d.append(data['maxIncrease3']) w.writerow(d) f.close()
from flask import request from flask_api import FlaskAPI from exchange.Exchange import Exchange from exchange.model.OrderBookRequest import NewOrder, Cancel # EB looks for an 'application' callable by default. application = FlaskAPI(__name__) application.config["DEBUG"] = True application.config['SECRET_KEY'] = 'secret!' exchange = Exchange(application.config["DEBUG"]) @application.route("/") def index(): return exchange.publish_lob() @application.route("/api/lob") def publish_lob(): return exchange.publish_lob() @application.route("/api/orders", methods=["GET"]) def view_orders(): return exchange.publish_orders() @application.route("/api/orders/<int:order_id>", methods=["GET"])