Hello guys I try to connect a trading bot on binance but I have some errors the last error is syntax Error
Can someone help me?
Hello guys I try to connect a trading bot on binance but I have some errors the last error is syntax Error
Can someone help me?
Read the error message and fix it. It is also possible that you ran into a line-length limit. A 4000 char line in a .py file is a bit ridiculous.
Hello, @Panlouk, and welcome to Python Software Foundation Discourse! We hope you enjoy the discussions here.
It would be of benefit for you to read the following:
Notice that the first of those two documents contains important information about how to format Python code for posting. It is much better to post code as properly formatted text, rather than as photographs or image captures. As explained in the document, copy and paste the Python code as plain text between two lines of triple backticks, as follows:
```
# Say hello to the world
print("Hello, world!")
```
thanks you for replying the algorithm above is the direct program as it runs, but in order to make it as fast as possible, I corrected it and i write the parameters without any error to run it directly in linux. it didnât give any error but it didnât run ⌠I have started it from the beginning from the file in visual studio code and I have this error. I tried to do it myself so as not to disturb the forum but I canât find the solution. can anyone to help?
THIS IS THE ALGORYTHM:
symbols = [âBTCâ,âETHâ,âLTCâ]
start_n_hours_ago = 48
def gather_data(symbols,start_n_hours_ago):
merge = False
for symbol in symbols:
klines = client.get_historical_klines(symbol=fâ{symbol}USDTâ,
interval=client.KLINE_INTERVAL_1HOUR,
start_str=str(datetime.now()-timedelta(hours=start_n_hours_ago)))
cols = [âOpenTimeâ,
fâ{symbol}-USD_Openâ,
fâ{symbol}-USD_Highâ,
fâ{symbol}-USD_Lowâ,
fâ{symbol}-USD_Closeâ,
fâ{symbol}-USD_volumeâ,
âClosetimeâ,
fâ{symbol}-QuoteAssetVolumeâ,
fâ{symbol}-NumberOfTradesâ,
fâ{symbol}-TBBAVâ,
fâ{symbol}-TBQAVâ,
fâ{symbol}-ignoreâ]
df = pd.DataFrame(klines,columns=cols)
if âmergeâ == True:
dfs = pd.merge(df,dfs,how=âinnerâ,on=[âOpenTimeâ,âCloseTimeâ])
else:
dfs = df
merge = True
dfs[âOpenTimeâ] = [datetime.fromtimestamp(ts / 1000) for ts in dfs[âOpenTimeâ]]
dfs[âCloseTimeâ] = [datetime.fromtimestamp(ts / 1000) for ts in dfs[âClosetimeâ]]
for col in dfs.columns:
if not âTimeâ in col:
dfs[col] = dfs[col].astype(float)
for symbol in symbols:
dfs[fâ{symbol}_smaâ] = sma(dfs[fâ{symbol}-USD_Closeâ],window=20)
dfs[fâ{symbol}_upper_bandâ], dfs[fâ{symbol}_lower_bandâ] = bollinger_band(data=dfs[fâ{symbol}-USD_Closeâ],
sma=dfs[fâ{symbol}_smaâ],
nstd=3)
dfs.dropna(inplace=True)
THIS IS THE ERROR:
Output exceeds the size limit. Open the full output data in a text editor
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py:3803, in Index.get_loc**(self, key, method, tolerance)** 3802 try: â 3803 return self._engine.get_loc(casted_key) 3804 except KeyError as err: File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas_libs\index.pyx:138, in pandas._libs.index.IndexEngine.get_loc**()** File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas_libs\index.pyx:165, in pandas._libs.index.IndexEngine.get_loc**()** File pandas_libs\hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item**()** File pandas_libs\hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item**()** KeyError: âBTC-USD_Closeâ The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[46], line 40 37 dfs[col] = dfs[col].astype(float) 39 for symbol in symbols: â> 40 dfs[fâ{symbol}_smaâ] = sma(dfs[fâ{symbol}-USD_Closeâ],window=20) 41 dfs[fâ{symbol}_upper_bandâ], dfs[fâ{symbol}_lower_bandâ] = bollinger_band(data=dfs[fâ{symbol}-USD_Closeâ],
âŚ
3808 # InvalidIndexError. Otherwise we fall through and re-raise 3809 # the TypeError. 3810 self._check_indexing_error(key) KeyError: âBTC-USD_Closeâ
I have try everything except the ( except key error ) pls if someone know to help me.
Thanks in advance
Please wrap code in triple backticks to preserve the formatting:
```python
if True:
print(''Hello world!')
```
Also wrap the traceback in triple backticks.
I noticed the line:
if "merge" == True:
The condition is always false because every string != False
. I assume you meant:
if merge == True:
Thereâs also:
for symbol in symbols:
klines = client.get_historical_klines(...)
This calls client.get_historical_klines
multiple times, binding klines
to each result in turn, so after the loop finishes, klines
will be bound to the last result only; the the previous results will have been discarded.
Thanks you for support i appreciate. About the merge you have right i have do this for experiment because i have in terminal an error (merge is not defined) but i forgot it. Now about the klines i thing have understand what you say but i dont know how to write it correct. Now the next problem is this
THIS IS THE ALGORYTHM:
symbols = ["BTC","ETH","LTC"]
start_n_hours_ago = 48
def gather_data(symbols,start_n_hours_ago):
merge = False
for symbol in symbols:
klines = client.get_historical_klines(symbol=f'{symbol}USDT',
interval=client.KLINE_INTERVAL_1HOUR,
start_str=str(datetime.now()-timedelta(hours=start_n_hours_ago)))
cols = ['OpenTime',
f'{symbol}-USD_Open',
f'{symbol}-USD_High',
f'{symbol}-USD_Low',
f'{symbol}-USD_Close',
f'{symbol}-USD_volume',
'Closetime',
f'{symbol}-QuoteAssetVolume',
f'{symbol}-NumberOfTrades',
f'{symbol}-TBBAV',
f'{symbol}-TBQAV',
f'{symbol}-ignore']
df = pd.DataFrame(klines,columns=cols)
if merge == True:
dfs = pd.merge(df,dfs,how='inner',on=['OpenTime','CloseTime'])
else:
dfs = df
merge = True
dfs['OpenTime'] = [datetime.fromtimestamp(ts / 1000) for ts in dfs['OpenTime']]
dfs['CloseTime'] = [datetime.fromtimestamp(ts / 1000) for ts in dfs["Closetime"]]
for col in dfs.columns:
if not 'Time' in col:
dfs[col] = dfs[col].astype(float)
for symbol in symbols:
dfs[f'{symbol}_sma'] = sma(dfs[f'{symbol}-USD_Close'],window=20)
dfs[f'{symbol}_upper_band'], dfs[f'{symbol}_lower_band'] = bollinger_band(data=dfs[f'{symbol}-USD_Close'],
sma=dfs[f'{symbol}_sma'],
nstd=3)
dfs.dropna(inplace=True)
THIS IS THE NEW ERROR:
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[58], line 26
23 df = pd.DataFrame(klines,columns=cols)
25 if merge == True:
---> 26 dfs = pd.merge(df,dfs,how='inner',on=['OpenTime','CloseTime'])
29 else:
30 dfs = df
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\reshape\merge.py:110, in merge(left, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)
93 @Substitution("\nleft : DataFrame or named Series")
94 @Appender(_merge_doc, indents=0)
95 def merge(
(...)
108 validate: str | None = None,
109 ) -> DataFrame:
--> 110 op = _MergeOperation(
111 left,
112 right,
113 how=how,
114 on=on,
115 left_on=left_on,
116 right_on=right_on,
117 left_index=left_index,
118 right_index=right_index,
...
-> 1850 raise KeyError(key)
1852 # Check for duplicates
1853 if values.ndim > 1:
KeyError: 'CloseTime'
Thanks in advance for support
ok i solve it this but i have again the classic errorâŚ
symbols = ["BTC","ETH","LTC"]
start_n_hours_ago = 48
def gather_data(symbols,start_n_hours_ago):
merge = False
for symbol in symbols:
klines = client.get_historical_klines(symbol=f'{symbol}USDT',
interval=client.KLINE_INTERVAL_1HOUR,
start_str=str(datetime.now()-timedelta(hours=start_n_hours_ago)))
cols = ['OpenTime',
f'{symbol}-USD_Open',
f'{symbol}-USD_High',
f'{symbol}-USD_Low',
f'{symbol}-USD_Close',
f'{symbol}-USD_volume',
'Closetime',
f'{symbol}-QuoteAssetVolume',
f'{symbol}-NumberOfTrades',
f'{symbol}-TBBAV',
f'{symbol}-TBQAV',
f'{symbol}-ignore']
df = pd.DataFrame(klines,columns=cols)
dfs = df
merge=False
if merge == True:
dfs = pd.merge(df,dfs,how='inner',on=['OpenTime','CloseTime'])
else:
dfs = df
merge = True
dfs['OpenTime'] = [datetime.fromtimestamp(ts / 1000) for ts in dfs['OpenTime']]
dfs['CloseTime'] = [datetime.fromtimestamp(ts / 1000) for ts in dfs['Closetime']]
for col in dfs.columns:
if not 'Time' in col:
dfs[col] = dfs[col].astype(float)
for symbol in symbols:
dfs[f'{symbol}_sma'] = sma(dfs[f'{symbol}-USD_Close'],window=20)
dfs[f'{symbol}_upper_band'], dfs[f'{symbol}_lower_band'] = bollinger_band(data=dfs[f'{symbol}-USD_Close'],
sma=dfs[f'{symbol}_sma'],
nstd=3)
dfs.dropna(inplace=True)
AND THE ERROR:
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py:3803, in Index.get_loc(self, key, method, tolerance)
3802 try:
-> 3803 return self._engine.get_loc(casted_key)
3804 except KeyError as err:
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\_libs\index.pyx:138, in pandas._libs.index.IndexEngine.get_loc()
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\_libs\index.pyx:165, in pandas._libs.index.IndexEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'BTC-USD_Close'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[87], line 43
40 dfs[col] = dfs[col].astype(float)
42 for symbol in symbols:
---> 43 dfs[f'{symbol}_sma'] = sma(dfs[f'{symbol}-USD_Close'],window=20)
44 dfs[f'{symbol}_upper_band'], dfs[f'{symbol}_lower_band'] = bollinger_band(data=dfs[f'{symbol}-USD_Close'],
...
3808 # InvalidIndexError. Otherwise we fall through and re-raise
3809 # the TypeError.
3810 self._check_indexing_error(key)
KeyError: 'BTC-USD_Close'
if somewne know please to tell me one magic command
Look at the indentation:
def gather_data(symbols,start_n_hours_ago):
merge = False
for symbol in symbols:
klines = client.get_historical_klines(symbol=f'{symbol}USDT',
That defines a function called gather_data
that contains only 1 line, merge = False
. The following line is not indented, so itâ and the remaining lines are not part of the function.
As for the rest of it, I donât know enough about it or what youâre trying to do. Are you trying to create a dataframe for each symbol. If yes, then youâll need to indent correctly to tell Python the extent of functions, loops, etc.
Thank you for replying and sorry for confusion but as i have say is my first complicate bot i donât have big experience with python. i only have do some other most simple bots. i will donât say you lye you have know already probably i donât have big experience⌠Now about the question what i try to do, i try to make a automatic trading bot is not unpossible the cryptocurrency banks give you keys for this reason or other trading apps.
Thanks you for support
guys i found it thanks for now i dont need any help i will resume with new when i stack again thanks very match for support
Hello again i am one last step before the bot launch i must to define 2 parameters (gather_data and get states) but i cant because when i go to define i block the other commands please if some know to help me
the not defined commands are in 28 and 29 lines df = gather_data(symbols,48)
states = get_states(df,symbols)
symbols = ['BTC','ETH','LTC']
start_n_hours_ago = 48
balance_unit = 'USDT'
first = True
BUY_AMOUNT_USDT = 300
precision = {}
for symbol in symbols:
precision[symbol] = client.get_symbol_info(f'{symbol}USDT')['quotePrecision']
from os import truncate
while True:
if (datetime.now().second % 10 == 0) or first:
if (datetime.now().minute == 0 and datetime.now().second == 10) or first:
# refresh data
first = False
df = gather_data(symbols,48)
states = get_states(df,symbols)
print('Current state of the market:')
print(states)
try:
print('\n')
if balance_unit == 'USDT': # looking to buy
for symbol in symbols:
ask_price = float(client.get_orderbook_ticker(symbol = f'{symbol}USDT')['askPrice'])
lower_band = df[f'{symbol}_lower_band'].iloc[-1]
print(f'{symbol}: ask price {ask_price} | lower_band {lower_band}')
if ask_price < lower_band and states[symbol] == 'inside': #buy signal
##########################
buy_order = client.order_limit_buy(symbol=f'{symbol}USDT',
quantity=truncate(BUY_AMOUNT_USDT / ask_price, precision[symbol]),
price=ask_price)
start = datetime.now()
while True:
time.sleep(1)
buy_order = client.get_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
# resolve buy order
seconds_since_buy = (datetime.now() - start).seconds
print(seconds_since_buy)
if float(buy_order['executedQty']) == 0 and seconds_since_buy > 60*60:
# no fill
client.cancel_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
break
if float(buy_order['executedQty']) != 0 and float(buy_order['executedQty']) != float(buy_order['origQty']) and seconds_since_buy > 60*60:
#partial fill
client.cancel_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
balance_unit = symbol
break
if float(buy_order['executedQty']) == float(buy_order['origQty']):
# complety filled
balance_unit = symbol
break
#########################
balance_unit = symbol
break
if balance_unit != 'USDT': # looking to sell
bid_price = float(client.get_orderbook_ticker(symbol = f'{balance_unit}USDT') ['bidPrice'])
upper_band = df[f'{balance_unit}_upper_band'].iloc[-1]
if bid_price > upper_band and states[balance_unit] == 'inside': # sell signal
#######################
client.order_market_sell(symbol=buy_order['symbol'],
quantity=truncate(float(buy_order['executedQty']), precision[buy_order['symbol'].replace('USDT','')]))
print('sell')
#######################
balance_unit = 'USDT'
time.sleep(1)
except Client.BinanceAPIException as e:
print (e.status_code)
print (e.message)
if someone know to tell me please
thanks in advance
I notice that you appear to be using truncate
from the os
module to truncate a number to an integer, but that function is for truncating a file to a specific length. You should be using int
(or possible floor
from the math
module) instead.
thanks you for replying and support one last issue and finish please if you know
THIS IS THE ERROR:
FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
dfx = dfx.append(mask, ignore_index=True)
AND THIS IS THE ALGORYTHM:
def gettrigger(self):
dfx = pd.DataFrame()
for i in range(self.lags + 1):
mask = (self.df['%K'].shift(i) < 20) & (self.df['%D'].shift(i) < 20)
dfx = dfx.append(mask, ignore_index=True)
return dfx.sum(axis=0)
this is not exactly error if you know please help me.
thanks in advance
Itâs very simple. As it says, frame.append
is deprecated and will be removed in a future version of pandas, so you should use pandas.concat
instead.
Change:
dfx = dfx.append(mask, ignore_index=True)
to:
dfx = pd.concat([dfx, mask], ignore_index=True)
Will .append
work? At the moment, yes, in the version of pandas that youâre currently using, but in a future version it wonât, so you might as well fix it now while youâre writing the code to save yourself future work.
Thanks you so match for direct reply i changed but now i have this something say to me the algorithm going for the garbage. Do you know if i remove this pandas version and replace with the previews version will be working? Thanks you
THIS IS THE ERROR:
FutureWarning: In a future version, object-dtype columns with all-bool values will not be included in reductions with bool_only=True. Explicitly cast to bool dtype instead. dfx = pd.concat([dfx, mask], ignore_index=True)
Output exceeds the [size limit](command:workbench.action.openSettings?[). Open the full output data [in a text editor](command:workbench.action.openLargeOutput?4341087d-1179-4a01-ac59-89e03d305e4d)
**---------------------------------------------------------------------------** **ValueError** Traceback (most recent call last) Cell **In[14], line 1** **----> 1** inst.decide() Cell **In[11], line 18**, in Signals.decide**(self)** 17 def decide(self): **---> 18** self.df['trigger'] = np.where(self.gettrigger(), 1, 0) 19 self.df['Buy'] = np.where((self.df.trigger) & 20 (self.df['%K'].between(20,80)) & (self.df['%D'].between(20,80)) 21 & (self.df.rsi > 50) & (self.df.macd > 0), 1, 0) File **c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py:3978**, in DataFrame.__setitem__**(self, key, value)** 3975 self._setitem_array([key], value) 3976 else: 3977 # set column **-> 3978** self._set_item(key, value) File **c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py:4172**, in DataFrame._set_item**(self, key, value)** 4162 def _set_item(self, key, value) -> None: 4163 """ 4164 Add series to DataFrame in specified column. 4165 **(...)** 4170 ensure homogeneity.
...
564 "does not match length of index " 565 f"({len(index)})" 566 ) **ValueError**: Length of values (1) does not match length of index (67)
AND THIS IS THE CORRECTED CODE:
def gettrigger(self):
dfx = pd.DataFrame()
for i in range(self.lags + 1):
mask = (self.df['%K'].shift(i) < 20) & (self.df['%D'].shift(i) < 20)
dfx = pd.concat([dfx, mask], ignore_index=True)
return dfx.sum(axis=0)
Thanks in advance for support
if you know the answer and you have the pleasure to help me tell me to post all the errors in code thanks in advance.
Thats the code thanks in advance
Cell In[26], line 1 inst.decide() (this is just for test)
class Signals:
def __init__(self,df, lags):
self.df = df
self.lags = lags
def gettrigger(self):
dfx = pd.DataFrame()
for i in range(self.lags + 1):
mask = (self.df['%K'].shift(i) < 20) & (self.df['%D'].shift(i) < 20)
dfx = pd.concat([dfx, mask], ignore_index=True) # dfx = pd.concat([dfx, mask], ignore_index=True)
return dfx.sum(axis=0) # dfx = dfx.append(mask, ignore_index=True)
# pd.concat([dfx],axis=1) ############
def decide(self):
self.df['trigger'] = np.where(self.gettrigger(), 1, 0)
self.df['Buy'] = np.where((self.df.trigger) &
(self.df['%K'].between(20,80)) & (self.df['%D'].between(20,80))
& (self.df.rsi > 50) & (self.df.macd > 0), 1, 0)
THE ERRORS:
FutureWarning: In a future version, object-dtype columns with all-bool values will not be included in reductions with bool_only=True. Explicitly cast to bool dtype instead.
dfx = pd.concat([dfx, mask], ignore_index=True) # dfx = pd.concat([dfx, mask], ignore_index=True)
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[26], line 1
----> 1 inst.decide()
Cell In[24], line 20, in Signals.decide(self)
19 def decide(self):
---> 20 self.df['trigger'] = np.where(self.gettrigger(), 1, 0)
21 self.df['Buy'] = np.where((self.df.trigger) &
22 (self.df['%K'].between(20,80)) & (self.df['%D'].between(20,80))
23 & (self.df.rsi > 50) & (self.df.macd > 0), 1, 0)
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py:3980, in DataFrame.__setitem__(self, key, value)
3977 self._setitem_array([key], value)
3978 else:
3979 # set column
-> 3980 self._set_item(key, value)
File c:\Users\Antonio alien\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py:4174, in DataFrame._set_item(self, key, value)
4164 def _set_item(self, key, value) -> None:
4165 """
4166 Add series to DataFrame in specified column.
4167
(...)
4172 ensure homogeneity.
...
574 "does not match length of index "
575 f"({len(index)})"
576 )
ValueError: Length of values (1) does not match length of index (67)