Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import date, timedelta, datetime
- import yfinance as yf
- from pynput.mouse import Button, Controller as mo
- from pynput.keyboard import Key, Controller as ke
- import time
- from yahoo_fin import stock_info as si
- import numpy as np
- from requests import get
- from requests.exceptions import RequestException
- from contextlib import closing
- from bs4 import BeautifulSoup
- """
- User-setup
- """
- #Trade button
- tradeB = (1356,275)
- #Sell button
- sellB = (432, 348)
- #Buy button
- buyB = (590, 350)
- #Stop Loss/Limit button
- stopLossB = (601, 404)
- #Point Away field
- pointsAwayF = (430, 509)
- #Submit button
- sumbitB = (416, 727)
- #Close X
- closeB = (1578,665)
- #Sumbit Close
- submitCloseB = (417,560)
- stockName = "^DJI"
- stockURL = "https://markets.businessinsider.com/futures/dow-futures"
- delay = 0.2
- stopLoss = 131
- """
- User-setup complete
- """
- mouse = mo()
- keyboard = ke()
- running = False
- def log_error(e):
- """
- It is always a good idea to log errors.
- This function just prints them, but you can
- make it do anything.
- """
- print(e)
- def is_good_response(resp):
- """
- Returns true if the response seems to be HTML, false otherwise
- """
- content_type = resp.headers['Content-Type'].lower()
- return (resp.status_code == 200
- and content_type is not None
- and content_type.find('html') > -1)
- def simple_get(url):
- """
- Attempts to get the content at `url` by making an HTTP GET request.
- If the content-type of response is some kind of HTML/XML, return the
- text content, otherwise return None
- """
- try:
- with closing(get(url, stream=True)) as resp:
- if is_good_response(resp):
- return resp.content
- else:
- return None
- except RequestException as e:
- log_error('Error during requests to {0} : {1}'.format(url, str(e)))
- return None
- def GetCurrentPrice(url):
- raw_html = simple_get(url)
- html = BeautifulSoup(raw_html, "html.parser")
- # Getting all span where the class is named "push.-data"
- mydivs = html.findAll("span", {"class": "push-data"})
- temp = str(mydivs[0])
- # Getting the first index of where the price is in the string.
- firstIndex = temp.find('">') + 2
- # Getting the last index of where the price is in the string.
- lastIndex = temp.find('</span>') # index before span.
- # Getting the price from the string
- price = temp[firstIndex:lastIndex]
- # Formating xx,xxx.xx -> xxxxx.xx
- formatted = price.replace(',', '')
- return float(formatted)
- #state: Long = True, short = False.
- def buyStock(state):
- #Universal
- mouse.position = (tradeB[0],tradeB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- if(state == True):
- #Buy
- mouse.position = (buyB[0], buyB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- elif (state == False):
- #Sell
- mouse.position = (sellB[0], sellB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- #Click stop / limit
- mouse.position = (stopLossB[0], stopLossB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- #Ready to type stop loss points.
- mouse.position = (pointsAwayF[0], pointsAwayF[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- #Type 131
- keyboard.type(str(stopLoss))
- time.sleep(delay)
- #Submit
- mouse.position = (sumbitB[0], sumbitB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- #Def done
- def getYesterdayStockPrice():
- if(datetime.now().weekday() == 0):
- yesterday = date.today() - timedelta(days=2) # This is indirectly getting fridays stockprice
- temp = yf.download(stockName, yesterday, yesterday)
- return np.array(temp["Close"])[0]
- elif (datetime.now().weekday() > 0 & datetime.now().weekday() <= 4):
- yesterday = date.today() # This is indirectly getting yesterdays stockprice
- temp = yf.download(stockName, yesterday, yesterday)
- return np.array(temp["Close"])[0]
- #Run script
- def run():
- tstart = GetCurrentPrice(stockURL)
- print("Current stock price: " + str(tstart))
- yesterdayStockPrice = getYesterdayStockPrice()
- print("Yesterdays close price: " + str(yesterdayStockPrice))
- time.sleep(0.5)
- #If todays price is bigger than yesterdays, then buy.
- if(tstart > yesterdayStockPrice):
- buyStock(True)
- elif (tstart < yesterdayStockPrice):
- buyStock(False)
- else:
- print("ERROR, same price yesterday as today.")
- def closePosition():
- #Close X
- mouse.position = (closeB[0], closeB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(0.1)
- #Close Submit
- mouse.position = (submitCloseB[0], submitCloseB[1])
- time.sleep(delay)
- mouse.click(Button.left)
- time.sleep(delay)
- print("Closed position, at: " + str(datetime.now().strftime("%H:%M:%S")))
- #THE LOOP, which checks if it is weekend, and if not, then gets all the data.
- while True:
- if(datetime.now().weekday() >= 0 and datetime.now().weekday() <= 4):
- currentTime = datetime.now().strftime("%H:%M:%S")
- print(currentTime)
- if(running == False):
- if (currentTime == "15:29:58"):
- run()
- running = True
- elif(running == True):
- if(currentTime == "21:59:58"):
- closePosition()
- running = False
- else:
- print("WEEKEND")
- time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement