# Python binance trading bot

**URL:** <https://discuss.python.org/t/python-binance-trading-bot/22804>\
**Category:** Python Help\
**Tags:** help\
**Created:** [January 15, 2023, 5:02pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804 "2023-01-15T17:02:20Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 15, 2023, 5:02pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/1 "2023-01-15T17:02:20Z")

</div>

Hello guys I try to connect a trading bot on binance but I have some errors the last error is syntax Error

 ![IMG_20230115_143209](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/a/a067eafd266a9b668ce3d237536b90ae05893334.jpeg)

Can someone help me?

---

<div class="post-metadata">

**Author:** ![tjreedy](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tjreedy/32/137_2.png) [@tjreedy](https://discuss.python.org/u/tjreedy)\
**Post date:** [January 15, 2023, 6:16pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/2 "2023-01-15T18:16:19Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Quercus](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/quercus/32/31483_2.png) [@Quercus](https://discuss.python.org/u/Quercus)\
**Post date:** [January 15, 2023, 9:24pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/3 "2023-01-15T21:24:01Z")

</div>

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:

- [Python Discourse Quick Start](https://discuss.python.org/t/python-discourse-quick-start/116)
- [About Discussions on Python.org](https://discuss.python.org/about)

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!")
```

````

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 20, 2023, 1:52am UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/6 "2023-01-20T01:52:17Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)\
**Post date:** [January 20, 2023, 2:25am UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/7 "2023-01-20T02:25:15Z")

</div>

Please wrap code in triple backticks to preserve the formatting:

````auto
```python
if True:
    print(''Hello world!')
```

````

Also wrap the traceback in triple backticks.

I noticed the line:

```python
if "merge" == True:

```

The condition is always false because every string != `False`. I assume you meant:

```python
if merge == True:

```

There’s also:

```python
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.

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 20, 2023, 11:56am UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/8 "2023-01-20T11:56:26Z")

</div>

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:

```auto
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

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 20, 2023, 1:25pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/9 "2023-01-20T13:25:40Z")

</div>

ok i solve it this but i have again the classic error…

```auto
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 🙄

---

<div class="post-metadata">

**Author:** ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)\
**Post date:** [January 20, 2023, 5:14pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/10 "2023-01-20T17:14:46Z")

</div>

Look at the indentation:

```python
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.

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 20, 2023, 6:11pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/11 "2023-01-20T18:11:24Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 20, 2023, 9:13pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/12 "2023-01-20T21:13:24Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 21, 2023, 7:44pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/13 "2023-01-21T19:44:48Z")

</div>

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)

```auto
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

---

<div class="post-metadata">

**Author:** ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)\
**Post date:** [January 22, 2023, 6:48pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/15 "2023-01-22T18:48:26Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 27, 2023, 5:38pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/16 "2023-01-27T17:38:32Z")

</div>

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:

```auto
 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

---

<div class="post-metadata">

**Author:** ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)\
**Post date:** [January 27, 2023, 6:24pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/17 "2023-01-27T18:24:53Z")

</div>

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:

```python
dfx = dfx.append(mask, ignore_index=True)

```

to:

```python
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.

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 27, 2023, 6:43pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/18 "2023-01-27T18:43:04Z")

</div>

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:

```auto
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:

```auto
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

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 28, 2023, 2:49pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/19 "2023-01-28T14:49:58Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Panlouk](https://avatars.discourse-cdn.com/v4/letter/p/258eb7/32.png) [@Panlouk](https://discuss.python.org/u/Panlouk)\
**Post date:** [January 28, 2023, 3:12pm UTC](https://discuss.python.org/t/python-binance-trading-bot/22804/20 "2023-01-28T15:12:01Z")

</div>

Thats the code thanks in advance

Cell **In[26], line 1** inst.decide() (this is just for test)

```auto
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:

```auto
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)

```
