python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

Help with websocket kline functionality

Open Technorocker opened this issue 8 years ago • 8 comments

Dont know if anyone else is having this issue but I keep getting a remotedisconnected error popping up lately. `Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request six.raise_from(e, None) File "", line 2, in raise_from File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 383, in _make_request httplib_response = conn.getresponse() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 1331, in getresponse response.begin() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 297, in begin version, status, reason = self._read_status() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 266, in _read_status raise RemoteDisconnected("Remote end closed connection without" http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\requests\adapters.py", line 440, in send timeout=timeout File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\util\retry.py", line 357, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\packages\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request six.raise_from(e, None) File "", line 2, in raise_from File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\urllib3\connectionpool.py", line 383, in _make_request httplib_response = conn.getresponse() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 1331, in getresponse response.begin() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 297, in begin version, status, reason = self._read_status() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\http\client.py", line 266, in _read_status raise RemoteDisconnected("Remote end closed connection without" urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "D:/Programming Projects/Python Courses/BinanceBot/history.py", line 97, in average15m = movingaverage(pair, timeframe) File "D:/Programming Projects/Python Courses/BinanceBot/history.py", line 53, in movingaverage candles = client.get_klines(symbol=symbol, interval=interval) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\binance\client.py", line 689, in get_klines return self._get('klines', data=params) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\binance\client.py", line 206, in _get return self._request_api('get', path, signed, version, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\binance\client.py", line 180, in _request_api return self._request(method, uri, signed, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\binance\client.py", line 174, in _request response = getattr(self.session, method)(uri, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\site-packages\requests\adapters.py", line 490, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) `

I migrated my websocket manager into my main file recently but also been trying to figure out the stay alive problem from websocket disconnecting after 24 hour too.

heres my starting code for my websocket starting. Hopefully I can get some advice on what I'm doing wrong.

#Websocket Initialization
bm = BinanceSocketManager(config.bclient)
res_array = []
closing = []
FIXED_SIZE = 200

def initiate(sym):
        global bm
	# Setup Socket
	# then start the socket manager
	conn_key = bm.start_trade_socket(sym, process_message)
	# start the socket
	bm.start()
	return conn_key

def process_message(msg):
	global res_array, bm
	if msg['e'] == 'error':
		bm.stop_socket(conn)
		initiate(pair)
	else:
		# Insert at first position
		res_array.insert(0, msg)
		if len(res_array) > FIXED_SIZE:
			# Remove last message when btcres_array size is > of FIXED_SIZE
			del res_array[-1]
		return res_array #make_post_calculations(btcres_array)

Thanks for any help anyone can provide

Technorocker avatar Feb 23 '18 18:02 Technorocker

I think I solved my own problem, I've been using the API to get klines and I think its timing me out for too many requests. I still havent figured out the proper way to use the multiplex socket function quite yet so I've been just using the trade socket so far. If anyone could confirm thats my problem that would be much appreciated

Technorocker avatar Feb 23 '18 18:02 Technorocker

So I figured out that I'm using the API to call the klines, that was the initial error for the conneciton closing I'm pretty sure at this point.

Now I'm trying to get the websocket for klines working and I have it set to 5m intervals. but the list im making from the process_message isnt reading 5m candles, it seems to be reading every second. I'm very confused at how to pull klines from websocket. Im basically using the klines previously to build my averages on the closing price of each candle in which I make a short and long moving average to compare to.

now I cant even get a proper return from klines to do anything with at the moment

Heres my code that I'm trying to test with...

def kline_message(msg):
	global trade_array, bm
	# Insert at first position
	kline_array.insert(0, msg)
	if len(kline_array) > FIXED_SIZE:
		# Remove last message when btcres_array size is > of FIXED_SIZE
		del kline_array[-1]
	return kline_array #make_post_calculations(btcres_array)

bm = BinanceSocketManager(config.bclient)
#start any sockets here, i.e a trade socket
conn_key = bm.start_trade_socket(pair, trade_message)
conn_kline = bm.start_kline_socket(pair, kline_message, interval='5m')
#then start the socket manager
bm.start()

for dict in kline_array:
	print('Start time',dict['k']['t'])
	print('End time  ',dict['k']['T'])
	print('Price',dict['k']['c'],'\n')

and when I run it I get this result...

Pair is BTCUSDT
Trade array is full
Fulllist size is: 2
Fulllist size is: 3
Fulllist size is: 4
Fulllist size is: 5
Price Array is Full, Starting cycle
kline [{'e': 'kline', 'E': 1519420984232, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745167, 'o': '9960.00000000', 'c': '9938.62000000', 'h': '9990.00000000', 'l': '9930.88000000', 'v': '57.74235400', 'n': 879, 'x': False, 'q': '575461.07340441', 'V': '32.23194300', 'Q': '321310.73478000', 'B': '0'}}, {'e': 'kline', 'E': 1519420982470, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745137, 'o': '9960.00000000', 'c': '9944.19000000', 'h': '9990.00000000', 'l': '9930.88000000', 'v': '56.64272600', 'n': 849, 'x': False, 'q': '564529.75052133', 'V': '31.96071400', 'Q': '318613.33634534', 'B': '0'}}, {'e': 'kline', 'E': 1519420980372, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745129, 'o': '9960.00000000', 'c': '9943.73000000', 'h': '9990.00000000', 'l': '9930.88000000', 'v': '56.38112600', 'n': 841, 'x': False, 'q': '561928.38243373', 'V': '31.70908800', 'Q': '316111.15160880', 'B': '0'}}, {'e': 'kline', 'E': 1519420978074, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745109, 'o': '9960.00000000', 'c': '9943.74000000', 'h': '9990.00000000', 'l': '9935.00000000', 'v': '55.37500200', 'n': 821, 'x': False, 'q': '551931.86183365', 'V': '31.36127300', 'Q': '312652.79951458', 'B': '0'}}, {'e': 'kline', 'E': 1519420976062, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745090, 'o': '9960.00000000', 'c': '9938.96000000', 'h': '9990.00000000', 'l': '9935.00000000', 'v': '54.29442700', 'n': 802, 'x': False, 'q': '541186.96871803', 'V': '30.28741000', 'Q': '301974.59025320', 'B': '0'}}, {'e': 'kline', 'E': 1519420973913, 's': 'BTCUSDT', 'k': {'t': 1519420800000, 'T': 1519421099999, 's': 'BTCUSDT', 'i': '5m', 'f': 21744289, 'L': 21745060, 'o': '9960.00000000', 'c': '9940.00000000', 'h': '9990.00000000', 'l': '9940.00000000', 'v': '51.30769400', 'n': 772, 'x': False, 'q': '511490.10670343', 'V': '28.51674500', 'Q': '284365.01108533', 'B': '0'}}]
Start time 1519420800000
End time   1519421099999
Price 9938.62000000 

Start time 1519420800000
End time   1519421099999
Price 9944.19000000 

Start time 1519420800000
End time   1519421099999
Price 9943.73000000 

Start time 1519420800000
End time   1519421099999
Price 9943.74000000 

Start time 1519420800000
End time   1519421099999
Price 9938.96000000 

Start time 1519420800000
End time   1519421099999
Price 9940.00000000 

from what I can tell its giving me second by second results. Am I missing something?

Technorocker avatar Feb 23 '18 21:02 Technorocker

So I changed up my code to not call the klines API as much in order to test if it was cuaing a rate limit error and it still is causing hte above error sometime between 10 min and 30 min of running. Soooo... Now I have 2 problems. This connection keeps disconnecting and I dont understand the klines websocket output. Can someone please help me, Ive been working on this bot for almost a month now and am getting discouraged that I can ever get this thing running smoothly.

Any help would be most appreciated

Technorocker avatar Feb 24 '18 05:02 Technorocker

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md At the binance official api docs, it is mentioned as: "The Kline/Candlestick Stream push updates to the current klines/candlestick every second." Basically they update you with the progress of the latest kline.

As a workaround i use the api to get the latest 2 klines. list=client.get_klines(symbol=self.market, interval=self.interval, limit=2)

list[1] #is the very last kline which is in progress, so not finalised list[0] #is what i need

bilgecetin avatar Feb 26 '18 07:02 bilgecetin

Thanks for the reply, I will try and incorporate how to use the klines for getting a moving average like the API call

Technorocker avatar Feb 27 '18 00:02 Technorocker

@Technorocker - Did you make any progress with how to use Kline data to get MA, RSI etc... ?

rootscript avatar Mar 10 '18 11:03 rootscript

Thanks for checking, I actually havent yet. From what I am gathering the kline socket feeds me data every second and the interval I give it sets the false and true end tag but I still have no idea how to catch say every 5m or 15m or whichever timeframe I want to watch for. At this point im using the trade socket for closing price and using alot of time.sleep calls for spacing out my while loop in my program.

Technorocker avatar Mar 10 '18 14:03 Technorocker

I am not sure if you are still trying to solve this or not but there is a work around I use that works pretty good. Here it is `depth_arr = np.array[len(sym)][60] temp_buff = [] buffer = [] def process_message(msg): global buffer mykeys = ['s','b','a'] global temp_buff

buff_size = len(buffer)
tb_size = len(temp_buff)

if tb_size < 10 and buff_size <= 10:
    temp_buff.append(msg.copy())

elif tb_size == 10 and buff_size <= 10:
    buffer.append(msg.copy())
    temp_buff = []

else:
    del buffer[0]
    buffer.append(msg.copy())`

basically, I create a temp list to hold variables and when it reaches a certain size, it writes the amount in the buffer. The code is still incomplete but I think you can figure out the rest. It writes every 10 seconds for me but you could change it to (n minutes)*60 to get your time frame roughly correct. It might not be exactly 15 minutes but will be within a second or two.

Not sure why the post is only showing part of my code as actual code but I think you can figure out what is code and what isn't

CJ1976 avatar Jun 11 '18 10:06 CJ1976