def on_message(ws, message): ''' Control the message received from ''' mess = json.loads(message) if mess['e'] == 'kline': kln = mess['k'] if kln['x'] is True: symbol = kln['s'].upper() new_kln = { '_t': int(kln['t']), '_o': float(kln['o']), '_h': float(kln['h']), '_l': float(kln['l']), '_c': float(kln['c']), '_v': float(kln['q']) } SymKlns[symbol].append(new_kln) print( '%d. %s\t' % (len(SymKlns[symbol]), symbol) + timestr(new_kln['_t']) + '\t' + \ ''.join(['{:>3}:{:<10}'.format(k, v) for k,v in iter(new_kln.items()) if not k=='_t'])) elif mess['e'] == 'depthUpdate': symbol = mess['s'].upper() bids, asks = mess['b'], mess['a'] new_bidask = { '_t': int(mess['T']), '_b1': float(bids[0][0]), '_b2': float(bids[1][0]), '_a1': float(asks[0][0]), '_a2': float(asks[1][0]) } BidAsk[symbol].append(new_bidask) print( '%d. %s\t' % (len(BidAsk[symbol]), symbol) + timestr(new_bidask['_t']) + '\t' + \ ''.join(['{:>3}:{:<10}'.format(k, v) for k,v in iter(new_bidask.items()) if not k=='_t']) )
def addcate(partnerid, parentid, name): '添加菜谱分类' db = newdb() db.cursor.execute('SELECT MAX(idx) from fd_categories where ptid=%(ptid)s', {'ptid': partnerid}) idx = db.cursor.fetchone()[0] + 1 db.cursor.execute( ''' INSERT INTO fd_categories ( cpid, ptid, name, idx, createtime) VALUES ( %(cpid)s, %(ptid)s, %(name)s, %(idx)s, %(createtime)s ) ''', { 'cpid': parentid, 'ptid': partnerid, 'name': name, 'idx': idx, 'createtime': utility.timestr() }) print utility.timestr() db.conn.commit() db.cursor.close() db.conn.close()
def __str__(self): ''' Print out infomation of the signal ''' s = 'Singal info: ' + self.symbol gen_ = ' status:' + str(self.status) + ' side:' + str( self.side) + ' type:' + str(self.orderType) + ' quantity:' + str( self.get_quantity()) if self.is_waiting() or self.is_expired(): id_ = ' Id:None ' price_ = ' price:' + str(self.price) + ' time:' + timestr( self.startTime, end='s') elif self.is_ordered(): id_ = ' Id:' + str(self.orderId) if self.orderType == 'LIMIT': price_ = ' price:' + str(self.limitPrice) + ' TIF:' + str( self.timeInForce) + ' time:' + timestr(self.startTime, end='s') else: price_ = ' type:' + str(self.orderType) + ' time:' + timestr( self.orderTime, end='s') elif self.is_active(): id_ = ' Id:' + str(self.orderId) if self.orderType == 'LIMIT': price_ = ' price:' + str(self.excPrice) + ' TIF:' + str( self.timeInForce) + ' time:' + timestr(self.excTime, end='s') else: price_ = ' price:' + str(self.excPrice) + ' time:' + timestr( self.excTime, end='s') elif self.is_cnt_ordered(): gen_ = ' status:' + str(self.status) + ' side:' + str( self.counter_order()['side']) + ' type:' + str( self.cntType) + ' quantity:' + str(self.get_quantity()) id_ = ' Id:' + str(self.cntorderId) if self.cntType == 'LIMIT': price_ = ' price:' + str(self.cntlimitPrice) + ' TIF:' + str( self.timeInForce) + ' time:' + timestr(self.cntTime, end='s') else: price_ = ' type:' + str(self.cntType) + ' time:' + timestr( self.cntTime, end='s') elif self.is_closed(): gen_ = ' status:' + str(self.status) + ' side:' + str( self.counter_order()['side']) + ' type:' + str( self.cntType) + ' quantity:' + str(self.get_quantity()) id_ = ' Id: ' + str(self.cntorderId) price_ = ' price:' + str(self.clsPrice) + ' time:' + timestr( self.clsTime, end='s') if self.stopLoss is None: sl_ = 'None' else: sl_ = str(self.stopLoss) if self.takeProfit is None: tp_ = 'None' else: tp_ = str(self.takeProfit) if self.timeLimit is None: tl_ = 'None' else: tl_ = str(int(self.timeLimit / sec_in_ms)) exits_ = ' exits:[' + sl_ + ', ' + tp_ + ', ' + tl_ + ']' s += id_ + gen_ + price_ + exits_ return s
def header_print(testnet, client): ''' Print general information of the trading session ''' t_server, t_local = client.timestamp(), time.time() * 1000 print('\tTestnet: %s' % str(testnet)) print('\tServer Time at Start: %s' % timestr(t_server)) print('\tLocal Time at Start: %s, \tOffset (local-server): %d ms\n' % (timestr(t_local), (t_local - t_server))) try: bal_st = pd.DataFrame(client.balance()) bal_st['updateTime'] = [timestr(b) for b in bal_st['updateTime']] print('\nBeginning Balance Info: \n') print(bal_st) except Exception: print('\nFail to connect to client.balance: \n')
def on_message(ws, message): ''' Control the message received from ''' mess = json.loads(message) if mess['e'] == 'kline': kln = mess['k'] if kln['x'] is True: symbol = kln['s'].upper() new_kln = { '_t': int(kln['t']), '_o': float(kln['o']), '_h': float(kln['h']), '_l': float(kln['l']), '_c': float(kln['c']), '_v': float(kln['q']) } SymKlns[symbol].append(new_kln) print( '%d. %s\t' % (len(SymKlns[symbol]), symbol) + timestr(new_kln['_t']) + '\t' + \ ''.join(['{:>3}:{:<10}'.format(k, v) for k,v in iter(new_kln.items()) if not k=='_t'])) elif mess['e'] == 'depthUpdate': ### PROBLEM 1 Insert your code to handle depthUpdate message ### pass
def header_print(testnet, client, portfolio, file): ''' Print general information of the trading session ''' t_server, t_local = client.timestamp(), time.time() * 1000 print_('\tTestnet: %s' % str(testnet), file) print_('\tServer Time at Start: %s' % timestr(t_server), file) print_( '\tLocal Time at Start: %s, \tOffset (local-server): %d ms\n' % (timestr(t_local), (t_local - t_server)), file) print_( '\t#LONG order : %d \t#SHORT order: %d \tOrder Size : %1.2f \n' % (portfolio.equityDist['BUY'], portfolio.equityDist['SELL'], portfolio.orderSize), file) try: bal_st = pd.DataFrame(client.balance()) bal_st['updateTime'] = [timestr(b) for b in bal_st['updateTime']] print_('\nBeginning Balance Info: \n', file) print_(bal_st, file) except Exception: print_('\nFail to connect to client.balance: \n', file)
def updatepage(partnerid,type,content): '更新页面内容' data={ 'ptid':partnerid, 'type':type, 'content':content, 'updatetime':utility.timestr() } row=newdb().query('UPDATE pt_page SET `content`=%(content)s,`updatetime`=%(updatetime)s WHERE `ptid`=%(ptid)s AND `type`=%(type)s',data) if row==0: newdb().query('INSERT INTO pt_page (`ptid`,`type`,`content`,`updatetime`) VALUES(%(ptid)s,%(type)s,%(content)s,%(updatetime)s)',data)
def updatefooditem(id, name, cid, pic, applySubm, note, desc, price=0, percent=1): ''' 更新食物 ''' _tstr = utility.timestr() db = newdb() db.cursor.execute( '''UPDATE fd_items SET cid=%(cid)s, name=%(name)s, img=%(img)s, price=%(price)s, percent=%(percent)s, applysubs=%(applysubs)s, note=%(note)s, updatetime=%(updatetime)s WHERE id=%(id)s''', { 'id': id, 'cid': cid, 'name': name, 'img': pic, 'price': price, 'percent': percent, 'applysubs': applySubm, 'note': note, 'updatetime': _tstr }) '更新描述' db.cursor.execute( '''UPDATE fd_itemprop SET description=%(description)s WHERE id=%(id)s''', { 'id': id, 'description': desc }) '提交到数据库' db.conn.commit() db.cursor.close() db.conn.close()
def updatepage(partnerid, type, content): '更新页面内容' data = { 'ptid': partnerid, 'type': type, 'content': content, 'updatetime': utility.timestr() } row = newdb().query( 'UPDATE pt_page SET `content`=%(content)s,`updatetime`=%(updatetime)s WHERE `ptid`=%(ptid)s AND `type`=%(type)s', data) if row == 0: newdb().query( 'INSERT INTO pt_page (`ptid`,`type`,`content`,`updatetime`) VALUES(%(ptid)s,%(type)s,%(content)s,%(updatetime)s)', data)
def upbank(memberid,bankname,bankaccount,status=1): '更新银行帐号信息' data={ 'memberid':memberid, 'bankname':bankname, 'bankaccount':bankaccount, 'status':status, 'updatetime':utility.timestr() }; row=newdb().query('UPDATE mm_bank SET bankname=%(bankname)s,bankaccount=%(bankaccount)s,status=%(status)s,updatetime=%(updatetime)s where memberid=%(memberid)s',data) if row== 0: row=newdb().query('INSERT INTO mm_bank (memberid,bankname,bankaccount,status,updatetime) VALUES (%(memberid)s,%(bankname)s,%(bankaccount)s,%(status)s,%(updatetime)s)',data) return row!=0
def upbank(memberid, bankname, bankaccount, status=1): '更新银行帐号信息' data = { 'memberid': memberid, 'bankname': bankname, 'bankaccount': bankaccount, 'status': status, 'updatetime': utility.timestr() } row = newdb().query( 'UPDATE mm_bank SET bankname=%(bankname)s,bankaccount=%(bankaccount)s,status=%(status)s,updatetime=%(updatetime)s where memberid=%(memberid)s', data) if row == 0: row = newdb().query( 'INSERT INTO mm_bank (memberid,bankname,bankaccount,status,updatetime) VALUES (%(memberid)s,%(bankname)s,%(bankaccount)s,%(status)s,%(updatetime)s)', data) return row != 0
def create_member(member,partnerid,tgid=0): db=newdb() timestr=utility.timestr() try: db.cursor.execute('''INSERT INTO members ( username, password, sex, realname, avatar, phone, address, qq, email, birthday, regtime, regip, lastlogintime, state) VALUES ( %(username)s, %(password)s, %(sex)s, %(realname)s, %(avatar)s, %(phone)s, %(address)s, %(qq)s, %(email)s, %(birthday)s, %(regtime)s, %(regip)s, %(lastlogintime)s, 1) ''', { 'username':member.username, 'password':encryptPwd(member.username,member.password), #hashlib.md5(member.password).hexdigest(), 'sex':member.sex, 'realname':member.realname, 'avatar':member.avatar, 'phone':member.phone, 'address':member.address, 'qq':member.qq, 'email':member.email, 'birthday':member.birthday, 'regtime':timestr, 'regip':member.regip, 'lastlogintime':'' }) db.cursor.execute('select id from members where username=%(user)s',{'user':member.username}) memberID=db.cursor.fetchone()[0] #关系表 db.cursor.execute('''INSERT INTO mm_relations (memberid, cardid, tgid, regmid) VALUES ( %(memberid)s, %(cardid)s, %(tgid)s, %(regmid)s )''', { 'memberid':memberID, 'cardid':'', 'tgid':tgid, 'regmid':partnerid } ) #帐户表 db.cursor.execute('''INSERT INTO mm_account (memberid, balance, totalfee, totalcharge, totalpay, updatetime ) VALUES (%(memberid)s, %(balance)s, %(totalfee)s, %(totalcharge)s, %(totalpay)s, %(updatetime)s) ''', { 'memberid':memberID, 'balance':0, 'totalfee':0, 'totalcharge':0, 'totalpay':0, 'updatetime':timestr }) db.conn.commit() except: db.conn.rollback() db.conn.close()
def main(args): start_time = time.time() testnet = True filename = str(int(time.time())) if testnet: # Testnet apikey = '' ### INSERT your api key here ### scrkey = '' ### INSERT your api secret here ### else: # Binance apikey = '' scrkey = '' if testnet: fileout = "report/testnet-" + filename else: fileout = "report/" + filename insIds = ['BTCUSDT', 'ETHUSDT', 'BCHUSDT', 'BNBUSDT'] # Generate Client object client = Client(apikey, scrkey, testnet=testnet) client.change_position_mode(dualSide='true') # Generate Portfolio object portfolio = Portfolio(client, tradeIns=insIds) long, short = portfolio.equity_distribution(longPct=0.25, shortPct=0.25, currency='USDT', orderPct=0.05) portfolio.position_locks() print_('\n' + barstr('', length=100, space_size=0), fileout) print_(barstr('BINANCE TRADING', length=100, space_size=5), fileout) print_(barstr('', length=100, space_size=0) + '\n', fileout) print_('\n' + barstr('Generating Models', length=100, space_size=5) + '\n', fileout) # Generate Models object models = {} for i in range(len(portfolio.tradeIns)): symbol = portfolio.tradeIns[i] client.change_leverage(symbol, 1) _data = MarketData(testnet=testnet, symbol=symbol) model = TradingModel(symbol=symbol, testnet=testnet, modelType='bollinger', marketData=_data, pdObserve=pd_ob, pdEstimate=pd_es, orderSize=portfolio.orderSize) model.build_initial_input() only_pos = 'BOTH' if symbol in portfolio.locks['BUY']: model.add_signal_lock(slock='BUY') only_pos = 'SELL ONLY' elif symbol in portfolio.locks['SELL']: model.add_signal_lock(slock='SELL') only_pos = 'BUY ONLY' models[symbol] = model print_( '\tFinish generating model for %s - positions: %s' % (symbol, only_pos), fileout) print_( '\n' + barstr('Start Data Streaming', length=100, space_size=5) + '\n', fileout) header_print(testnet, client, portfolio, fileout) print('\n\tPre-processing Time = %f' % (time.time() - start_time)) print_('\nStream updating for {} minutes...'.format(pd_ob * min_in_candle), fileout) signals = wss_run(portfolio, client, testnet, ['@kline_1m'], models, fileout) session_summary(signals, fileout) print_('\n\tLocal Time at Close: %s ' % timestr(time.time() * 1000), fileout) print_( barstr(text='Elapsed time = {} seconds'.format( round(time.time() - start_time, 2))), fileout) print_(barstr(text="", space_size=0), fileout) os._exit(1)
'DASHUSDT' ] stream = ['@depth5@500ms'] BidAsk = {} AggTrades = {} SymKlns = {} client = Client(apikey, scrkey, testnet=testnet) client.change_position_mode(dualSide='true') for symbol in insIds: client.change_leverage(symbol, 1) BidAsk[symbol] = [] AggTrades[symbol] = [] SymKlns[symbol] = [] print('\n' + barstr(text='Start Data Streaming') + '\n') header_print(testnet, client) print('\nStream updating...') listen_key = client.get_listen_key() ws = websocket.WebSocketApp(f'{client.wss_way}{listen_key}', on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() print('\n\tLocal Time at Close: %s \n' % timestr(time.time() * 1000)) print( barstr(text='Elapsed time = {} seconds'.format( round(time.time() - start_time, 2)))) print(barstr(text="", space_size=0)) os._exit(1)
def addfooditem(name, cid, pic, applySubm, note, desc, price=0, percent=1): ''' 新增食物 ''' _tstr = utility.timestr() _id = None db = newdb() db.cursor.execute( '''INSERT INTO fd_items ( cid, name, img, price, percent, applysubs, note, state, updatetime) VALUES ( %(cid)s, %(name)s, %(img)s, %(price)s, %(percent)s, %(applysubs)s, %(note)s, %(state)s, %(updatetime)s )''', { 'cid': cid, 'name': name, 'img': pic, 'price': price, 'percent': percent, 'applysubs': applySubm, 'note': note, 'state': 1, 'updatetime': _tstr }) '获取插入的索引' db.cursor.execute( 'SELECT id FROM fd_items WHERE cid=%(cid)s AND updatetime=%(uptime)s', { 'cid': cid, 'uptime': _tstr }) _id = db.cursor.fetchone()[0] '插入描述' db.cursor.execute( '''INSERT INTO fd_itemprop (id,description)VALUES (%(id)s,%(description)s)''', { 'id': _id, 'description': desc }) '提交到数据库' db.conn.commit() db.cursor.close() db.conn.close()
def create_member(member, partnerid, tgid=0): db = newdb() timestr = utility.timestr() try: db.cursor.execute( '''INSERT INTO members ( username, password, sex, realname, avatar, phone, address, qq, email, birthday, regtime, regip, lastlogintime, state) VALUES ( %(username)s, %(password)s, %(sex)s, %(realname)s, %(avatar)s, %(phone)s, %(address)s, %(qq)s, %(email)s, %(birthday)s, %(regtime)s, %(regip)s, %(lastlogintime)s, 1) ''', { 'username': member.username, 'password': encryptPwd(member.username, member.password ), #hashlib.md5(member.password).hexdigest(), 'sex': member.sex, 'realname': member.realname, 'avatar': member.avatar, 'phone': member.phone, 'address': member.address, 'qq': member.qq, 'email': member.email, 'birthday': member.birthday, 'regtime': timestr, 'regip': member.regip, 'lastlogintime': '' }) db.cursor.execute('select id from members where username=%(user)s', {'user': member.username}) memberID = db.cursor.fetchone()[0] #关系表 db.cursor.execute( '''INSERT INTO mm_relations (memberid, cardid, tgid, regmid) VALUES ( %(memberid)s, %(cardid)s, %(tgid)s, %(regmid)s )''', { 'memberid': memberID, 'cardid': '', 'tgid': tgid, 'regmid': partnerid }) #帐户表 db.cursor.execute( '''INSERT INTO mm_account (memberid, balance, totalfee, totalcharge, totalpay, updatetime ) VALUES (%(memberid)s, %(balance)s, %(totalfee)s, %(totalcharge)s, %(totalpay)s, %(updatetime)s) ''', { 'memberid': memberID, 'balance': 0, 'totalfee': 0, 'totalcharge': 0, 'totalpay': 0, 'updatetime': timestr }) db.conn.commit() except: db.conn.rollback() db.conn.close()
def setstatus(partnerid, orderid, status): '设置订单状态' db = newdb() timestr = utility.timestr() #更新订单状态 result = db.cursor.execute( 'UPDATE pt_orders SET status=%(status)s WHERE id=%(id)s AND ptid=%(ptid)s', { 'id': orderid, 'ptid': partnerid, 'status': status }) == 1 if result: if status == 3: #将此次消费记入会员账户 db.cursor.execute( 'SELECT mid,pay FROM pt_orders WHERE id=%(id)s and mid<>0', {'id': orderid}) row = db.cursor.fetchone() _memberid = None if row == None else row[0] #会员订餐 if _memberid != None: _amount = row[1] db.cursor.execute( '''UPDATE mm_account SET totalpay=totalpay+%(amount)s WHERE memberid=%(memberid)s''', { 'memberid': _memberid, 'amount': _amount }) #万绿园返现 _pt = user.getpartnerbyid(partnerid) if _pt['user'] == 'wly': bytes = ( 1, #100%分成 0.02, #上级 0.01, #上上级 0.1 #消费者自己 ) _backfee = row[1] * bytes[0] _mid = _memberid tpl_str = u'来自订单:%s(商家:%s,会员:%s)收入¥%s元.' '给自己返现' if bytes[3] != 0: db.cursor.execute('''INSERT INTO mm_account_incomelog ( memberid, type, fee, log, recordtime) VALUES ( %(memberid)s, %(type)s, %(fee)s, %(log)s, %(recordtime)s )''', { 'memberid':_mid, 'type':'backcash', 'fee':_backfee*bytes[3], 'log':u'订单:%s返现¥%s元'%\ ( orderid, str(_backfee*bytes[3]) ), 'recordtime':timestr }) db.cursor.execute( 'UPDATE mm_account SET totalfee=totalfee+%(amount)s,balance=balance+%(amount)s,updatetime=%(uptime)s WHERE memberid=%(memberid)s', { 'amount': _backfee * bytes[3], 'memberid': _mid, 'uptime': timestr }) '给上线返现' i = 0 while _mid != 0 and i < 2: db.cursor.execute( 'SELECT tgid FROM mm_relations WHERE memberid=%(memberid)s', {'memberid': _mid}) _mid2 = db.cursor.fetchone()[0] if _mid2 != 0: '获取产生的用户' db.cursor.execute( 'SELECT username,realname FROM members WHERE id=%(memberid)s', {'memberid': _mid}) _username = db.cursor.fetchone()[0] _fee = _backfee * bytes[i + 1] #返现金额 _log=tpl_str%\ ( orderid, _pt['name'], _username, str(_fee) ) db.cursor.execute( '''INSERT INTO mm_account_incomelog ( memberid, type, fee, log, recordtime) VALUES ( %(memberid)s, %(type)s, %(fee)s, %(log)s, %(recordtime)s )''', { 'memberid': _mid2, 'type': 'backcash', 'fee': _fee, 'log': _log, 'recordtime': timestr }) db.cursor.execute( 'UPDATE mm_account SET totalfee=totalfee+%(amount)s,balance=balance+%(amount)s,updatetime=%(uptime)s WHERE memberid=%(memberid)s', { 'amount': _fee, 'memberid': _mid2, 'uptime': timestr }) _mid = _mid2 i += 1 #会员订餐处理结束 #提交更改到数据库 db.commit() db.conn.close() return result
def setstatus(partnerid,orderid,status): '设置订单状态' db=newdb() timestr=utility.timestr() #更新订单状态 result=db.cursor.execute('UPDATE pt_orders SET status=%(status)s WHERE id=%(id)s AND ptid=%(ptid)s', { 'id':orderid, 'ptid':partnerid, 'status':status })==1 if result: if status==3: #将此次消费记入会员账户 db.cursor.execute('SELECT mid,pay FROM pt_orders WHERE id=%(id)s and mid<>0',{'id':orderid}) row=db.cursor.fetchone() _memberid=None if row==None else row[0] #会员订餐 if _memberid!=None: _amount=row[1] db.cursor.execute('''UPDATE mm_account SET totalpay=totalpay+%(amount)s WHERE memberid=%(memberid)s''', { 'memberid':_memberid, 'amount':_amount } ) #万绿园返现 _pt=user.getpartnerbyid(partnerid) if _pt['user']=='wly': bytes=( 1, #100%分成 0.02, #上级 0.01, #上上级 0.1 #消费者自己 ) _backfee=row[1]*bytes[0] _mid=_memberid tpl_str=u'来自订单:%s(商家:%s,会员:%s)收入¥%s元.' '给自己返现' if bytes[3]!=0: db.cursor.execute('''INSERT INTO mm_account_incomelog ( memberid, type, fee, log, recordtime) VALUES ( %(memberid)s, %(type)s, %(fee)s, %(log)s, %(recordtime)s )''', { 'memberid':_mid, 'type':'backcash', 'fee':_backfee*bytes[3], 'log':u'订单:%s返现¥%s元'%\ ( orderid, str(_backfee*bytes[3]) ), 'recordtime':timestr }) db.cursor.execute('UPDATE mm_account SET totalfee=totalfee+%(amount)s,balance=balance+%(amount)s,updatetime=%(uptime)s WHERE memberid=%(memberid)s', { 'amount':_backfee*bytes[3], 'memberid':_mid, 'uptime':timestr } ) '给上线返现' i=0; while _mid!=0 and i<2: db.cursor.execute('SELECT tgid FROM mm_relations WHERE memberid=%(memberid)s',{'memberid':_mid}) _mid2=db.cursor.fetchone()[0] if _mid2!=0: '获取产生的用户' db.cursor.execute('SELECT username,realname FROM members WHERE id=%(memberid)s',{'memberid':_mid}) _username=db.cursor.fetchone()[0] _fee=_backfee*bytes[i+1] #返现金额 _log=tpl_str%\ ( orderid, _pt['name'], _username, str(_fee) ) db.cursor.execute('''INSERT INTO mm_account_incomelog ( memberid, type, fee, log, recordtime) VALUES ( %(memberid)s, %(type)s, %(fee)s, %(log)s, %(recordtime)s )''', { 'memberid':_mid2, 'type':'backcash', 'fee':_fee, 'log':_log, 'recordtime':timestr }) db.cursor.execute('UPDATE mm_account SET totalfee=totalfee+%(amount)s,balance=balance+%(amount)s,updatetime=%(uptime)s WHERE memberid=%(memberid)s', { 'amount':_fee, 'memberid':_mid2, 'uptime':timestr } ) _mid=_mid2 i+=1 #会员订餐处理结束 #提交更改到数据库 db.commit() db.conn.close() return result