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 ### 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 __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 header_print(client): ''' Print Local Time, Timezone and Account Balance Info ''' t_local = time.time() * 1000 print('\n' + barstr(text="", space_size=0)) print(barstr(text='IG Server Connecting Session Info')) print('\n\n\tDemo Server: %s' % str(demo)) print('\tLocal Time at Start: %s, \n\tServer Timezone Offset : UTC%+d' % (timestr(t_local), resp['timezoneOffset'])) print('\n\tAccount Balance info at Start:') try: accounts = client.account_details()['accounts'] for n in range(len(accounts)): info = { str(key): str(value) for key, value in iter(accounts[0].items()) } balance = { str(key): str(value) for key, value in iter(accounts[0]['balance'].items()) } print('\tAccount #{}:'.format(n)) print( "\tId : {accountId:<} \tType : {accountType:<} \tStatus : {status:<} \tCurrency : {currency:<}" .format(**info)) print( "\tBalance \tTotal : {balance:<} \tAvailable : {available:<}". format(**balance)) print('\n') except Exception: print('\tFAIL to connect to client.balance. \n')
def handle_response(self, enablePrint=True, on_message=None): ''' Process live message from IG Streaming Server Pass fucntion on_message to handle the messages differently ''' line = self._stream_response.readline().decode("utf-8").rstrip() if line != 'PROBE': if not bool(on_message): toks = line.rstrip('\r\n').split('|') item = self.subscriptions['item_names'][ int(toks[0].split(',')[-1]) - 1] pstr = {} for i in range(len(self.subscriptions['field_names'])): field = self.subscriptions['field_names'][i] value = LSClient._decode_field( toks[i + 1], prev=self._prevResp[item][field]) try: if field == 'UTM': value = timestr(int(value), end='s') except: pass pstr[field] = value self._prevResp[item] = pstr.copy() if enablePrint: print( "{:<35}".format(item), ''.join([ '{:>10} : {:<10}'.format(k, v) for k, v in iter(pstr.items()) ])) pstr['item'] = item return pstr else: return on_message(line)
def get_ticks(symbol, start_time, filepath): if not isinstance(start_time, int): start_time = int(pd.Timestamp(datetime.strptime(start_time, '%d %b %Y %H:%M:%S')).value/10**6) print("\nProcessing aggTrades for %s from %s \n" % (symbol, timestr(start_time, end='s'))) agg_trades = client.aggregate_trade_iter(symbol=symbol, start_str=start_time) trade_df = pd.DataFrame(list(agg_trades)).drop(['a', 'f','l','m','M'], axis=1) trade_df = trade_df.rename(columns={"p": "_p", "q": "_v", "T": "_t"}) trade_df['_p'] = trade_df['_p'].astype(float) trade_df['_v'] = trade_df['_v'].astype(float) rawfile = filepath + "aggtrades-%s.csv" % (symbol) trade_df.to_csv(rawfile) return trade_df
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 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']), fileout)
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') s += id_ + gen_ + price_ ### PROBLEM 2 : Insert your code here ### return s
demo = True if demo: # demo IG username = '' password = '' apikey = '' else: # IG username = '' password = '' apikey = '' """Client to connect to IG Server""" client = Client(username=username, password=password, api_key=apikey, demo=demo) resp = client.create_session(encrypted=True) header_print(client) """Multi-threading function. One can call data_stream() directly""" t1 = threading.Thread(target=data_stream) t1.setDaemon(True) t1.start() t1.join() 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 main(args): start_time = time.time() testnet = True filename = str(int(time.time())) if testnet: # Testnet # "key": "d782f0d42dcf016c32fd56a96d01bb0e120f78802d9de378cdb9fde2b6c841e8", #"secret": "1ec873bf3137868a9e12e57e8e19cfa5a3a38cec403b741d2f7cd881c51bfd72" apikey = 'd782f0d42dcf016c32fd56a96d01bb0e120f78802d9de378cdb9fde2b6c841e8' ### INSERT your api key here ### scrkey = '1ec873bf3137868a9e12e57e8e19cfa5a3a38cec403b741d2f7cd881c51bfd72' ### 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)