Python Forum
Trading Bot written in Python for Windows
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trading Bot written in Python for Windows
#1
Hello.

Absolutely no knowledge of Python human here:

Background:

Trading robot written in python for windows keep crashing when trying to execute. I have the latest version of python, with environment variables set correctly. CMD just seem to open for a couple seconds, hang then drop (close). I'm not sure whether its a poorly written python code or some dependency issue between windows/python.

Any ideas?

Additional note: Trading Bots can often be flagged up as viruses when they're not. In this case windows wouldn't allow completion of the download when it got to the compressed exe file in the program then kept flagging the archive as corrupt. Used a downlaod manager to bypass that. But still having issues with execution of the program. At this stage of analysis i'm trying to identify and eliminate whether its a pyhton issue, a windows issue or the file itself.
Reply
#2
I have removed you attachment(.py) file as there Api keys visible.
(Sep-26-2022, 03:41 PM)Pizzlew Wrote: CMD just seem to open for a couple seconds
You most first open cmd then run code.
There is lot to install,do you now how pip works?
This code look like someone testing stuff out,and may not work probably.
Here is code without Api keys.
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import sys, os


def override_where():
    """ overrides certifi.core.where to return actual location of cacert.pem"""
    # change this to match the location of cacert.pem
    return os.path.abspath("cacert.pem")


# is the program compiled?
if hasattr(sys, "frozen"):
    import certifi.core

    os.environ["REQUESTS_CA_BUNDLE"] = override_where()
    certifi.core.where = override_where

    # delay importing until after where() has been replaced
    import requests.utils
    import requests.adapters
    # replace these variables in case these modules were
    # imported before we replaced certifi.core.where
    requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
    requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()


# In[2]:


from binance.client import Client
from binance import ThreadedWebsocketManager
import pandas as pd
import datetime
from datetime import timedelta
import numpy as np
import time
import talib
import dateparser
import dateparser.data.date_translation_data.en
import websockets.legacy


# In[ ]:





# In[3]:


class LongShortTrader():
    def __init__ (self, symbol, bar_length, parameters, units, position = 0):
        self.symbol = symbol
        self.bar_length = bar_length
        #self.data = pd.DataFrame(columns = ["Open", "High","Low","Close","Volume","Complete"])
        self.available_intervals = ["1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h"]
        self.units = units
        self.position = position
        self.trades = 0 #NEW
        self.trade_values = [] #NEW
        
        
        ################################# add strategy specific attributes ##################################
        
        self.sma = parameters[0]
        self.timeperiod = parameters[1]
        self.dev = parameters[2]
        
        #####################################################################################################
        
    def __repr__(self):
        return "Shreya Bot| Symbol : {}, Bar Length : {}".format(self.symbol, self.bar_length)
        
    def start_trading(self, historical_days):
        self.twm = ThreadedWebsocketManager()
        self.twm.start()
        
        if self.bar_length in self.available_intervals:
            self.get_most_recent(symbol = self.symbol, interval = self.bar_length, days = historical_days)
            print(50* "-" + "\n")
            print("Connected to Binance | Starting Trading")
            print(50* "-" + "\n")
            self.twm.start_kline_socket(callback = self.stream_candles, symbol = self.symbol, interval = self.bar_length)
            self.twm.join()
            
        # "else" to be added later in the course
        
    def get_most_recent(self, symbol, interval, days):
    
        now = datetime.datetime.utcnow()
        past = str(now - timedelta(days = days))

        bars = client.get_historical_klines(symbol = symbol, interval = interval, 
                                            start_str = past, end_str = None, limit = 1000)
        #preparing our dataframe
        df = pd.DataFrame(bars)
        df["Date"] = pd.to_datetime(df.iloc[:,0], unit = "ms")
        df.columns = ["Open Time", "Open", "High", "Low", "Close", "Volume", "Close Time",
                     "Quote Asset Volume", "Number of Trades", "Taker Buy Base Asset Volume",                  
                      "Taker Buy Quote Asset Volume", "Ignore", "Date"]
        df = df[["Date","Open", "High", "Low", "Close", "Volume"]].copy()
        df.set_index("Date", inplace = True)

        for column in df.columns:
            df[column] = pd.to_numeric(df[column], errors = "coerce")

        df["Complete"] = [ True for row in range(len(df) - 1)] + [False]



        self.data = df 
 
        
    def stream_candles(self, msg):
        '''
           define how to process the incoming web socket messages
        '''

        #extract the required items from msg
        event_time = pd.to_datetime(msg["E"], unit = "ms")
        start_time = pd.to_datetime(msg["k"]["t"], unit = "ms")
        first    = float(msg["k"]["o"])
        high     = float(msg["k"]["h"])
        low      = float(msg["k"]["l"])
        close    = float(msg["k"]["c"])
        volume   = float(msg["k"]["v"])
        complete =       msg["k"]["x"]
        
        '''
        # stop trading session
        if self.trades == 50:
            self.twm.stop()
            if self.position == 1:
                order = client.create_order(symbol = self.symbol, side = "SELL", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL AND STOP")
                self.position = 0
                
            #elif self.position == -1:
                order = client.create_order(symbol = self.symbol, side = "BUY", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL AND STOP")
                self.position = 0                
                
            else:
                print("STOPPING ROBOT")
         '''      
            #more examples
            #if self.trades = x
            #if event_time >= datetime.datetime(2021, 11, 4, 9, 55)
            #if self.cum_profits >= x
              #execute the entire stop strategy

        #Print out
        #print(".", end = "", flush = False) #just print something to get a feedback (everything Okay!)
        #for x in range (0,5):  
        print("\r" , "SHREYA BOT RUNNING" + ".......", end =" ")
        #print(".", end = "", flush = True) #just print something to get a feedback (everything Okay!)
            
           



        #feed df (add new bar / update latest bar)
        self.data.loc[start_time] = [first, high, low, close, volume, complete]
        
        #prepare features and define strategy/trading positions whenever the latest bar is complete
        if complete == True:
            self.define_strategy()
            self.execute_trades()
  
        
    def define_strategy(self): #strategy specific
        
        df = self.data.copy()
        
        
        #*****************************. define your strategy here *************************************#
        df = df[["Close", "Volume"]].copy()
        df["Returns"] = np.log(df.Close.div(df.Close.shift(1))) #adding our returns
        df["SMA"] = df.Close.rolling(window=self.sma).mean()
        df["UpperBB"], df["MiddleBB"], df["LowerBB"] = talib.BBANDS(df["Close"], timeperiod=self.timeperiod, nbdevup=self.dev, nbdevdn=self.dev, matype=0)
        
        ## Buy Condition
        buycond1 = df["Close"] > df["SMA"]
        buycond2 = df["SMA"].shift(1) < df["SMA"] 
        buycond5 = df["SMA"].shift(2) < df["SMA"].shift(1)
        buycond6 = df["SMA"].shift(3) < df["SMA"].shift(2)
        buycond7 = df["SMA"].shift(4) < df["SMA"].shift(3)
        buycond8 = df["SMA"].shift(5) < df["SMA"].shift(4)
        buycond9 = df["SMA"].shift(6) < df["SMA"].shift(5)
        buycond10 = df["SMA"].shift(7) < df["SMA"].shift(6)
        buycond11 = df["Close"] < df["UpperBB"]

        ## Sell condition
        sellcond1 = df["Close"] < df["SMA"]
        sellcond2 = df["SMA"].shift(1) > df["SMA"]
        sellcond5 = df["SMA"].shift(2) > df["SMA"].shift(1)
        sellcond6 = df["SMA"].shift(3) > df["SMA"].shift(2)
        sellcond7 = df["SMA"].shift(4) > df["SMA"].shift(3)
        sellcond8 = df["SMA"].shift(5) > df["SMA"].shift(4)
        sellcond9 = df["SMA"].shift(6) > df["SMA"].shift(5)
        sellcond10 = df["SMA"].shift(7) > df["SMA"].shift(6)
        sellcond11 = df["Close"] > df["LowerBB"]

        #Trading Position        
        df["Position"] = 0
        df.loc[buycond2 & buycond5 & buycond6 & buycond7 & buycond8 & buycond9 & buycond10 & buycond11, "Position"] = 1
        df.loc[sellcond2 & sellcond5 & sellcond6 & sellcond7 & sellcond8 & sellcond9 & sellcond10 & sellcond11, "Position"] = -1
        
        #################################################################################################
                
        self.prepared_data = df.copy()
        
        
    def execute_trades(self):
        if self.prepared_data["Position"].iloc[-1] == 1: #if the position is long -> go/stay long
            if self.position == 0:
                order = client.create_order(symbol = self.symbol, side = "BUY", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING LONG")
                
            elif self.position == -1:
                order = client.create_order(symbol = self.symbol, side = "BUY", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL")
                time.sleep(0.1)
                order = client.create_order(symbol = self.symbol, side = "BUY", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING LONG")
            self.position = 1
                
        elif self.prepared_data["Position"].iloc[-1] == 0: #if the position is neutral -> go/stay neutral
            if self.position == 1:
                order = client.create_order(symbol = self.symbol, side = "SELL", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL")
                
            elif self.position == -1:
                order = client.create_order(symbol = self.symbol, side = "BUY", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL")
            self.position = 0                   
                
        if self.prepared_data["Position"].iloc[-1] == -1: #if the position is short -> go/stay short
            if self.position == 0:
                order = client.create_order(symbol = self.symbol, side = "SELL", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING SHORT")
                
            elif self.position == 1:
                order = client.create_order(symbol = self.symbol, side = "SELL", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING NEUTRAL")
                time.sleep(0.1)
                order = client.create_order(symbol = self.symbol, side = "SELL", type = "MARKET", quantity = self.units)
                self.report_trade(order, "GOING SHORT")               
            self.position = -1

                

            
    def report_trade(self, order, going):
        
        #extract data from order object
        side = order["side"]
        time = pd.to_datetime(order["transactTime"], unit = "ms")
        base_units = float(order["executedQty"])
        quote_units = float(order["cummulativeQuoteQty"])
        price = round(quote_units / base_units, 5)
        
        
        
        #calculating trading profits
        self.trades += 1
        if side == "BUY":
            self.trade_values.append(-quote_units)
            
        elif side == "SELL":
            self.trade_values.append(quote_units)
            
            
        if self.trades % 2 == 0:
            real_profit = round(np.sum(self.trade_values[-2:]), 3)
            self.cum_profits = round(np.sum(self.trade_values), 3)
                        
        else:
            real_profit = 0
            self.cum_profits = round(np.sum(self.trade_values[:-1]), 3)
            
            
        #print trade report
        print(2* "\n" + 100* "-")
        print("{} | {}".format(time, going))
        print("{} Base Units = {} | Quote Units = {} | Price = {} ".format(time, base_units, quote_units, price))
        print("{} Profit = {} | cumProfits = {}".format(time, real_profit, self.cum_profits))
        print(100* "-" + "\n")


# In[ ]:





# In[ ]:





# In[4]:


#api_key = "xxxxx"
#secret_key = "xxxxx"

print("Shreya Spot Trading Bot Activated...")
api_key = input("ENTER YOUR API KEY: ")
secret_key = input("ENTER YOUR BINANCE SECRET KEY : ")
tradk = input("ENTER YOUR EMAIL : ")
tradkp = input("ENTER YOUR PASSWORD : ")
units = input("ENTER YOUR TRADING VOLUME (MIN | 0.01 MAX = 10) : ")
test_value = input("ARE YOU TRADING ON Testnet OR Livenet? : ")
if test_value == "Testnet":
    testnet = True
elif test_value == "Livenet":
    testnet = False
else:
    print("Type either \"Testnet\" or \"livenet\"")
    test_value = input("ARE YOU TRADING ON Testnet OR Livenet? : ")
    
client = Client(api_key = api_key, api_secret = secret_key, tld = "com", testnet = testnet)
trader = LongShortTrader(symbol = "BTCUSDT", bar_length = "1h", parameters = (850, 295, 5), units = units)
print(trader)
#print("Shreya Robot Ended Successfully")
trader.start_trading(historical_days = 2)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  library for C but written in Python Skaperen 1 400 Apr-15-2024, 08:50 AM
Last Post: SandraYokum
  [Software suggestion] Video player written in Python? ThePhi 2 2,643 Dec-10-2018, 07:14 PM
Last Post: ThePhi
  Why isn’t there any good hacking books written in Python 3 Takeshio 8 11,359 Aug-26-2018, 09:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020