'How do I change this to use websockets binance python?
I've done this program, but don't know how to change this to use web sockets. If I use this as it is, I get an API error (too many calls) and tells me to use websockets.
Can you please help me?
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 13:23:22 2021
@author: tu madre es una foca
"""
# IMPORTING PACKAGES
import pandas as pd
from pandas import *
import numpy as np
#import matplotlib.pyplot as plt
import requests
from math import floor
from termcolor import colored as cl
import config003
from binance.streams import ThreadedWebsocketManager
from binance import ThreadedDepthCacheManager
from binance.client import Client
from binance.enums import *
from binance.streams import BinanceSocketManager
import asyncio
#from binance.streams import AsyncClient
import time
from datetime import datetime
client = Client(config003.API_KEY, config003.API_SECRET, tld='com')
#plt.style.use('fivethirtyeight')
#plt.rcParams['figure.figsize'] = (20,10)
symbolo=input("Enter a stock ticker symbol: ")
idate=input("Enter a since when you want to test symbol o por ejemplo 14 day ago UTC: ")
cantidad =input("enter a cantidad:")
leve=input("enter a leve:")
COMPRANDO=[None]
VENDIENDO=[None]
now = datetime.now()
#start_date=now
#idate="2017-12-21"
#symbolo='ATOMUSDT'
# EXTRACTING DATA
ii=1
while ii!=0:
symbol=symbolo
idate=idate
leve=leve
bm = BinanceSocketManager(client)
#bm.aggtrade_socket(symbolo)
#bm.start()
async def order_book(client, symbol):
order_book = await client.get_order_book(symbol=symbolo)
print(order_book)
async def kline_listener(client):
bm = BinanceSocketManager(client)
symbol = symbolo
res_count = 0
async with bm.kline_socket(symbol=symbol) as stream:
while True:
res = await stream.recv()
res_count += 1
print(res)
if res_count == 5:
res_count = 0
loop.call_soon(asyncio.create_task, order_book(client, symbol))
#INTERVALOS: 1HOUR 1MINUTE
#def get_historical_data(symbol):
def get_historical_data(symbolo,start_date):
klines = client.futures_historical_klines(symbolo,interval=Client.KLINE_INTERVAL_1MINUTE,start_str=idate)
#start = ["month_1"].values.astype('datetime64[D]')
df = pd.DataFrame(klines, columns=['Date',
'Open',
'High',
'Low',
'Close',
'Volume',
'Close time',
'Quote asset volume',
'Number of trades',
'Taker buy base asset volume',
'Taker buy quote asset volume',
'Ignore'])
df = df.drop(df.columns[[6, 7, 8, 9, 10, 11]], axis=1)
df['Date'] = pd.to_datetime(df['Date'], unit='ms')
df.set_index('Date', inplace=True, drop=True)
df['Open'] = df['Open'].astype(float)
df['High'] = df['High'].astype(float)
df['Low'] = df['Low'].astype(float)
df['Close'] = df['Close'].astype(float)
df['Volume'] = df['Volume'].astype(float)
# raw_df = requests.get(api_url).json()
# df = pd.DataFrame(raw_df['values']).iloc[::-1].set_index('datetime').asdtype(float)
#df = df[df.index >= start_date]
#df.index = pd.to_datetime(df.index)
return df
tsla = get_historical_data(symbolo, idate)
#print(df)
print(symbolo)
I've tried to do it with this (but doesnt seem to work propperly):
def trade_history(msg):
''' define how to process incoming WebSocket messages '''
if msg['e'] != 'error':
print(msg)
print(msg['c'])
print(msg['E'])
print(msg['o'])
print(msg['h'])
print(msg['l'])
print(msg['v'])
btc_price['last'] = msg['c']
btc_price['bid'] = msg['b']
btc_price['last'] = msg['a']
btc_price['error'] = False
indexes[0]=msg['E']
indexes[1]=msg['o']
indexes[2]=msg['h']
indexes[3]=msg['l']
indexes[4]=msg['v']
df = pd.DataFrame(data=indexes)
df['Date'] = pd.to_datetime(msg['E'], unit='ms')
df.set_index('Date', inplace=True, drop=True)
df['Open'] = df['o'].astype(float)
df['High'] = df['h'].astype(float)
df['Low'] = df['l'].astype(float)
df['Close'] = df['c'].astype(float)
df['Volume'] = df['v'].astype(float)
#candles=client.get_klines(symbol=symbolo)
#pd.DataFrame(columns=indexes, data=candles)
print(df)
return df
else:
btc_price['error'] = True
bsm = ThreadedWebsocketManager()
bsm.start()
please help, how can I make this work is it posible to get historical data from websockets? I need like historic data from 4 days , how can I implement this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|