#To do:
#-Strategy refine
#-Buy time in RL not correct
#-Load Backlog from file
#-GUI
#-Plotting in same window
#x
#


#Trading bot
import pip
import yfinance as yf
import numpy as np
import pandas as pd
import ta
import math
from math import sqrt
import matplotlib.pyplot as plt
import pandas_datareader as web
import pandas as pd
from scipy.signal import savgol_filter
from scipy import optimize
from sklearn import linear_model
from datetime import datetime
import sys
from ta.volatility import BollingerBands
import degiroapi
from degiroapi.product import Product
from degiroapi.order import Order
from degiroapi.utils import pretty_json
import schedule
import time
from tkinter import *


pd.set_option('display.max_columns', None)

class Stocks:
    Ticker = ['TWTR']
    TickerSeries = ['AAPL','AMD','SPCE','TWTR','NFLX','TSLA','PFE','ETSY', 'SURF', 'WATT', 'MOXC', 'PCG', 'SQ', 'RH', 'SBUX', 'COIN']


def init():
    #Initilize variables
    global Budget
    Budget = 1000
    global Support_counter
    Support_counter = 0

def Timer():
    global Hours
    global now
    now = datetime.now()
    Time = now.hour - datetime.strptime('15:30:00', '%H:%M:%S').hour
    Hours = str(Time) + 'h'
    return (Hours, now)

def Get_data(stock,range):
    #Get stock data
    global Stock_data
    Stock_data = yf.download(tickers=stock,period=range,interval='1m')
    #Get rid of unnecesary columns
    Stock_data = Stock_data.drop('Open',1)
    Stock_data = Stock_data.drop('High',1)
    Stock_data = Stock_data.drop('Low',1)
    Stock_data = Stock_data.drop('Close',1)
    DataSet = pd.DataFrame()
    DataSet = Stock_data.copy()
    return (DataSet)

def Get_data_range(stock,From,To):
    #Get stock data
    global Stock_data
    Stock_data = yf.download(tickers=stock,start=From,stop=To,interval='1m')
    #Get rid of unnecesary columns
    Stock_data = Stock_data.drop('Open',1)
    Stock_data = Stock_data.drop('High',1)
    Stock_data = Stock_data.drop('Low',1)
    Stock_data = Stock_data.drop('Close',1)
    DataSet = pd.DataFrame()
    DataSet = Stock_data.copy()
    return (DataSet)

def Data_init():
    global DataSet
    DataSet = pd.DataFrame()
    DataSet['Price'] = Stock_data['Adj Close'].round(4)
    DataSet['Price'].round(4)
    DataSet['Support'] = np.nan
    DataSet['Resistant'] = np.nan
    DataSet['Buy_Signal_Price'] = np.nan
    DataSet['Sell_Signal_Price'] = np.nan
    DataSet['Gain'] = np.nan
    DataSet['SuppLine'] = np.nan
    DataSet['ResLine'] = np.nan

    return (DataSet)

def Trading_History():
    global History
    History = pd.DataFrame()
    History['Buy Time'] = ''
    History['Stock'] = ''
    History['Buy Price'] = ''
    History['Amount'] = ''
    History['Sold'] = ''
    History['Sell Time'] = ''
    History['Sell Price'] = ''
    History['Gain'] = ''
    return ()

def Indicators(a,b,c,d):
    #Make SMA
    DataSet['SMA5'] = DataSet['Price'].rolling(window =  a).mean()
    DataSet['SMA30'] = DataSet['Price'].rolling(window = b).mean()
    DataSet['SMA45'] = DataSet['Price'].rolling(window = c).mean()
    DataSet['EMA360'] = DataSet['Price'].ewm(span = d).mean()
    return (DataSet)

def S_R(DataSet):
    Local_Max = np.nan
    Local_Min = np.nan
    Have_Min = 0
    Have_Max = 0
    for i in range (len(DataSet)):
        #Support
        if DataSet['Price'].iloc[i] < DataSet['Price'].iloc[i-1]:
            Local_Min = DataSet['Price'].iloc[i]
            DataSet['Resistant'].iloc[i-1] = Local_Max
            Local_Max = np.nan
        #Resistant
        if DataSet['Price'].iloc[i] > DataSet['Price'].iloc[i-1]:
            Local_Max = DataSet['Price'].iloc[i]
            DataSet['Support'].iloc[i-1] = Local_Min
            Local_Min = np.nan
    return (DataSet)

def LinearR (DataSet):

    DataSet['ID'] = np.arange(len(DataSet))

    LinearSuppData = pd.DataFrame()
    LinearSuppData = DataSet.copy()

    LinearResData = pd.DataFrame()
    LinearResData = DataSet.copy()

    LinearSuppData = LinearSuppData[LinearSuppData['Support'].notna()]
    LinearResData = LinearResData[LinearResData['Resistant'].notna()]

    DataSet['SuppMVA'] = LinearSuppData['Support'].rolling(window = 3).mean()
    DataSet['ResMVA'] = LinearResData['Resistant'].rolling(window = 3).mean()

    LinearSuppData.index = pd.to_numeric(pd.to_datetime(LinearSuppData.index))
    LinearResData.index = pd.to_numeric(pd.to_datetime(LinearResData.index))

    y_fit_Supp = LinearSuppData['Support'].to_numpy()
    x_fit_Supp = LinearSuppData['ID'].to_numpy().reshape(-1,1)

    y_fit_Res = LinearResData['Resistant'].to_numpy()
    x_fit_Res = LinearResData['ID'].to_numpy().reshape(-1,1)

    RegSuppLine = linear_model.LinearRegression()
    RegSuppLine.fit(x_fit_Supp,y_fit_Supp)

    RegResLine = linear_model.LinearRegression()
    RegResLine.fit(x_fit_Res,y_fit_Res)


    for i in range (len(DataSet)):
            DataSet['SuppLine'] = (DataSet['ID'] * RegSuppLine.coef_) + RegSuppLine.intercept_
            DataSet['ResLine'] = (DataSet['ID'] * RegResLine.coef_) + RegResLine.intercept_

    return(DataSet)

def BollingerBands(m,l,h,DataSet):

    BBSet = pd.DataFrame()
    BBSet = DataSet


    DataSet['BB_MAV'] = DataSet['Price'].rolling(window = m).mean()
    DataSet['BB_SD'] = DataSet['Price'].rolling(window = m).std()
    DataSet['BB_LO'] = DataSet['BB_MAV'] - (BBSet['BB_SD']*l)
    DataSet['BB_HI'] = DataSet['BB_MAV'] + (BBSet['BB_SD']*h)


    return(DataSet)


def Buy_Sell(DataSet, Stock):
    global Amount
    global History
    print (History)
    for i in range (len(DataSet)):
        #Buy conditions
        if (DataSet['Price'].iloc[i] <= DataSet['BB_LO'].iloc[i]) and (DataSet['Price'].iloc[i] < DataSet['SuppLine'].iloc[i] and DataSet['EMA360'].iloc[i] > DataSet['Price'].iloc[i]):
            try:
                if (not History['Stock'].iloc[History.loc[History['Sold'] == False].index[0]] == Stock):
                    (DataSet['Buy_Signal_Price'].iloc[i]) = (DataSet['Price'].iloc[i])
                    Amount = math.floor(Budget/(DataSet['Buy_Signal_Price'].iloc[i]))
                    History = History.append({'Buy Time': DataSet.index.time[i], 'Stock' : Stock, 'Buy Price' : round (DataSet['Buy_Signal_Price'][i], 4), 'Amount' : Amount, 'Sold' : False}, ignore_index=True)
                    #print('BUY!', Amount, 'of', Stocks.Ticker, 'for', DataSet['Buy_Signal_Price'][i])
            except IndexError:
                (DataSet['Buy_Signal_Price'].iloc[i]) = (DataSet['Price'].iloc[i])
                Amount = math.floor(Budget/(DataSet['Buy_Signal_Price'].iloc[i]))
                History = History.append({'Buy Time': DataSet.index.time[i], 'Stock' : Stock, 'Buy Price' : round (DataSet['Buy_Signal_Price'][i], 4), 'Amount' : Amount, 'Sold' : False}, ignore_index=True)
                #print('BUY!', Amount, 'of', Stocks.Ticker, 'for', DataSet['Buy_Signal_Price'][i])
        #Sell conditions
        if (not History['Sold'].all()):
            if (DataSet['Price'].iloc[i] >= DataSet['BB_HI'].iloc[i]) and (DataSet['Price'].iloc[i] > DataSet['ResLine'].iloc[i]) and (DataSet['EMA360'].iloc[i] < DataSet['Price'].iloc[i]) or ((DataSet['Price'][i]) <= (History['Buy Price'].iloc[History.loc[History['Sold'] == False].index[0]])*0.995):
                if (History['Stock'].iloc[History.loc[History['Sold'] == False].index[0]] == Stock):
                    DataSet['Sell_Signal_Price'].iloc[i] = DataSet['Price'].iloc[i]
                    for h in range (len(History)):
                        if (History['Stock'].iloc[h] == Stock and History['Sold'].iloc[h] == False):
                            History['Sold'].iloc[h] = True
                            History['Sell Time'].iloc[h] = DataSet.index.time[i]
                            History['Sell Price'].iloc[h] = round (DataSet['Sell_Signal_Price'][i], 4)
                            History['Gain'].iloc[h] = (History['Sell Price'].iloc[h] - History['Buy Price'].iloc[h])*Amount
                            #print('SELL!', Amount, 'of', Stocks.Ticker, 'for', DataSet['Sell_Signal_Price'][i])
    print(History)
    return(DataSet, History)

def Buy_Sell_RL(DataSet, Stock):
    global Amount
    global Bought
    global History
        #Buy conditions
    print((realprice[0]['data']['lastPrice'], '<=', DataSet['BB_LO'][-1]), (DataSet['Price'][-1], '<' , DataSet['SuppLine'][-1]), DataSet['EMA360'][-1],'>',DataSet['Price'][-1])
    print((realprice[0]['data']['lastPrice'], '>=', DataSet['BB_HI'][-1]), (DataSet['Price'][-1], '>', DataSet['ResLine'][-1]))
    if (realprice[0]['data']['lastPrice'] <= DataSet['BB_LO'][-1]) and (realprice[0]['data']['lastPrice'] < DataSet['SuppLine'][-1]) and (DataSet['EMA360'][-1] > realprice[0]['data']['lastPrice']):
        try:
            if (not History['Stock'].iloc[History.loc[History['Sold'] == False].index[0]] == Stock):
                Amount = math.floor(Budget/(DataSet['Price'][-1]))

                degiro.buyorder(Order.Type.LIMIT, Product(products[0]).id, 1, Amount, round (realprice[0]['data']['lastPrice'], 2))
                #Loging
                print('BUY!', Amount, 'of', Stock, 'for', realprice[0]['data']['lastPrice'])
                History = History.append({'Buy Time': DataSet.index.time[-1], 'Stock' : Stock, 'Buy Price' : round (realprice[0]['data']['lastPrice'], 4), 'Amount' : Amount, 'Sold' : False}, ignore_index=True)
        except IndexError:
            Amount = math.floor(Budget/(DataSet['Price'][-1]))

            degiro.buyorder(Order.Type.LIMIT, Product(products[0]).id, 1, Amount, round (realprice[0]['data']['lastPrice'], 2))
            #Loging
            print('BUY!', Amount, 'of', Stock, 'for', DataSet['Buy_Signal_Price'].tail())
            History = History.append({'Buy Time': DataSet.index.time[-1], 'Stock' : Stock, 'Buy Price' : round (realprice[0]['data']['lastPrice'], 4), 'Amount' : Amount, 'Sold' : False}, ignore_index=True)

    #Sell conditions
    if (not History['Sold'].all()):
        if (realprice[0]['data']['lastPrice'] >= DataSet['BB_HI'][-1]) and (realprice[0]['data']['lastPrice'] > DataSet['ResLine'][-1]) and (DataSet['EMA360'][-1] < realprice[0]['data']['lastPrice']) or ((realprice[0]['data']['lastPrice']) <= (History['Buy Price'].iloc[History.loc[History['Sold'] == False].index[0]])*0.998):
            if (History['Stock'].iloc[History.loc[History['Sold'] == False].index[0]] == Stock):

                degiro.sellorder(Order.Type.LIMIT, Product(products[0]).id, 1, Amount, round (realprice[0]['data']['lastPrice'], 2))
                print('SELL!', Amount, 'of', Stock, 'for', realprice[0]['data']['lastPrice'])

                for h in range (len(History)):
                    if (History['Stock'].iloc[h] == Stock and History['Sold'].iloc[h] == False):
                        History['Sold'].iloc[h] = True
                        History['Sell Time'].iloc[h] = DataSet.index.time[i]
                        History['Sell Price'].iloc[h] = round (realprice[0]['data']['lastPrice'], 4)
                        History['Gain'].iloc[h] = (History['Sell Price'].iloc[h] - History['Buy Price'].iloc[h])*Amount
    return(DataSet, History)

def Degiro_Cash():
    global degiro
    degiro = degiroapi.DeGiro()
    degiro.login("MoszneTrader", "B!z@nek77")

    cashfunds = degiro.getdata(degiroapi.Data.Type.CASHFUNDS)
    for data in cashfunds:
        print(data)

    return

def Degiro(Stock):
    global products
    global realprice
    products = degiro.search_products(Stock)
    realprice = degiro.real_time_price(Product(products[0]).id, degiroapi.Interval.Type.One_Day)
    print(Product(products[0]).symbol,realprice[0]['data']['lastPrice'])

    #if np.isnan(DataSet['Buy_Signal_Price'].iloc[-1]) == False:
        #degiro.buyorder(Order.Type.LIMIT, Product(products[0]).id, 1, Amount, realprice[0]['data']['lastPrice'])
        #print('BUY!', Amount, 'of', Stocks.Ticker, 'for', DataSet['Buy_Signal_Price'].tail())

    #if np.isnan(DataSet['Sell_Signal_Price'].iloc[-1]) == False:
        #degiro.sellorder(Order.Type.LIMIT, Product(products[0]).id, 1, Amount, realprice[0]['data']['lastPrice'])
        #print('SELL!', Amount, 'of', Stocks.Ticker, 'for', DataSet['Sell_Signal_Price'].tail())


#Ploting options
def Plot():
    #Ranges
    x = DataSet.index
    y = DataSet['Price']
    plt.figure(figsize=(16, 10))
    #plt.ylim([DataSet['Price'].min(),DataSet['Price'].max()])
    plt.plot(x,y, label = 'Price')

    #plt.plot(DataSet['SMA5'], label= 'SMA5')
    #plt.plot(DataSet['SMA30'], label= 'SMA30')
    #plt.plot(SMA45['Adj Close'], label= 'SMA45')
    plt.plot(DataSet['EMA360'], label = 'EMA360')

    plt.plot(DataSet['Buy_Signal_Price'], label = 'Buy', marker ='^', color = 'green', ms = 10)
    plt.plot(DataSet['Sell_Signal_Price'], label = 'Sell', marker ='v', color = 'red', ms = 10)

    plt.plot(DataSet['BB_MAV'], label = 'BolingerBand MAV', linestyle = '--', color = 'blue')
    plt.plot(DataSet['BB_HI'], label = 'BolingerBand High', linestyle = '--', color = 'green')
    plt.plot(DataSet['BB_LO'], label = 'BolingerBand Low', linestyle = '--', color = 'red')
    #plt.fill_between(BBSet['BB_HI'], BBSet['BB_LO'], alpha = 0.1)

    plt.plot(DataSet['SuppLine'], label = 'Support', color = 'green')
    plt.plot(DataSet['ResLine'], label = 'Resistant', color = 'red')
    #plt.scatter(DataSet.index,DataSet['Support'], color = 'green', label = 'Support', s = 4)
    #plt.scatter(DataSet.index,DataSet['Resistant'], color = 'red', label = 'Resistant', s = 4)
    plt.plot(DataSet['SuppMVA'], label = 'SupportMVA', color = 'green', linestyle = ':')
    plt.plot(DataSet['ResMVA'], label = 'ResistanMVA', color = 'red', linestyle = ':')

    plt.title(Stocks.Ticker)
    plt.ylabel('Price $')
    plt.xlabel('Time')
    plt.legend(loc='upper left')
    plt.show()

def GUI():
    return

def Tunning(Tickers):
    Row = -1
    TunningSet = pd.DataFrame()
    TunningSet['Stock'] = Tickers
    TunningSet['Transactions'] = np.nan
    TunningSet['Biggest_Winrate'] = np.nan
    TunningSet['Biggest_Gain'] = np.nan
    TunningSet['Best_m'] = np.nan
    TunningSet['Best_l'] = np.nan
    TunningSet['Best_h'] = np.nan
    TunningSet['Best_a'] = np.nan
    TunningSet['Best_b'] = np.nan
    TunningSet['Best_c'] = np.nan
    TunningSet['Best_d'] = np.nan
    for t in Tickers:
        Best_m = 0
        Best_l = 0
        Best_h = 0
        Best_d = 0
        Biggest_Winrate = 0
        Biggest_Gain = 0
        Row = Row + 1
        Wintrate = 0
        TotalTrans = 0
        Get_data(t,'6h')
        Data_init()

        DataCopy = DataSet.copy()
        for d in range(60,360,30):
            for m in range (16,22,2):
                for l in range (100,300,50):
                    for h in range (100,300,50):
                        DataCopy2 = DataCopy
                        S_R(DataSet)
                        LinearR(DataSet)
                        Indicators(5,15,30,d)
                        BollingerBands(m,l/100,h/100,DataCopy)
                        print('Current Step:','m',m,'l',l,'h',h,'d',d)
                        Buy_Sell(DataCopy)
                        print ('Curent Ticker:', t)
                        print ('Curent Winrate:',Winrate)
                        print('Biggest Winrate:',Biggest_Winrate)
                        print('Gains:', GainSum)
                        #Plot()
                        if (Winrate > Biggest_Winrate):
                            TotalTrans = Total
                            Biggest_Winrate = Winrate
                            Biggest_Gain = GainSum
                            Best_m = m
                            Best_l = l
                            Best_h = h
                            Best_d = d
                        DataCopy = DataCopy2
        TunningSet['Transactions'] = TotalTrans
        TotalTrans = 0
        TunningSet['Biggest_Winrate'].iloc[Row] = Biggest_Winrate
        TunningSet['Biggest_Gain'].iloc[Row] = Biggest_Gain
        TunningSet['Best_m'].iloc[Row] = Best_m
        TunningSet['Best_l'].iloc[Row] = Best_l
        TunningSet['Best_h'].iloc[Row] = Best_h
        TunningSet['Best_d'].iloc[Row] = Best_d
        #print('Best results:', Biggest_Winrate, Biggest_Gain)
        #print('Best m l h:', Best_m, Best_l/100, Best_h/100)
        print(TunningSet)
    return(TunningSet)

def Manual(Ticker):
    Get_data(Ticker,'4h')
    Degiro_Cash()
    Data_init()
    Trading_History()
    #Get_data_range(Stocks.Ticker,'2021-06-04 11:00:00-04:00','2021-06-4 13:00:00-04:00')
    Indicators(5,15,30,360)
    S_R(DataSet)
    LinearR(DataSet)
    BollingerBands(30,2.25,2.25,DataSet)
    Buy_Sell(DataSet, Ticker)
    Degiro(Ticker)
    Plot()
    now = datetime.now()
    now = now.date()
    History.to_csv(f'History_{now}.csv')
    #print(DataSet)
    return()

def Run(Tickers):
    Trading_History()
    History = pd.read_csv(f'History_RL{datetime.now().date()}.csv')
    while datetime.now() > datetime.now().replace(hour=15, minute=30, second=0, microsecond=0) and datetime.now() < datetime.now().replace(hour=22, minute=0, second=0, microsecond=0):
        print(datetime.now())
        Degiro_Cash()
        Timer();
        for t in Tickers:
            Get_data(t,'Hours')
            Data_init()
            #Get_data_range(Stocks.Ticker,'2021-06-04 11:00:00-04:00','2021-06-4 13:00:00-04:00')
            Indicators(5,15,30,360)
            S_R(DataSet)
            LinearR(DataSet)
            BollingerBands(30,2.25,2.25,DataSet)
            Degiro(t)
            Buy_Sell_RL(DataSet, t)
        print(History)
        current_date = datetime.now()
        current_date = now.date()
        History.to_csv(f'History_RL{current_date}.csv')
        time.sleep(15)
    else:
        print('It is not time yet!')
    return()

init()
GUI()
#Tunning(Stocks.TickerSeries)
#Manual('SPCE')
Run(Stocks.TickerSeries)

MainWindow = Tk()
MainWindow.title('Trading Bot')

F1 = Entry()
F1.pack()

#MainWindow.mainloop() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling