SHARE
TWEET

Untitled

a guest Feb 25th, 2020 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from datetime import date, timedelta, datetime
  2. import yfinance as yf
  3. from pynput.mouse import Button, Controller as mo
  4. from pynput.keyboard import Key, Controller as ke
  5. import time
  6. from yahoo_fin import stock_info as si
  7. import numpy as np
  8. from requests import get
  9. from requests.exceptions import RequestException
  10. from contextlib import closing
  11. from bs4 import BeautifulSoup
  12.  
  13. """
  14. User-setup
  15. """
  16.  
  17. #Trade button
  18. tradeB = (1356,275)
  19.  
  20. #Sell button
  21. sellB = (432, 348)
  22.  
  23. #Buy button
  24. buyB = (590, 350)
  25.  
  26. #Stop Loss/Limit button
  27. stopLossB = (601, 404)
  28.  
  29. #Point Away field
  30. pointsAwayF = (430, 509)
  31.  
  32. #Submit button
  33. sumbitB = (416, 727)
  34.  
  35. #Close X
  36. closeB = (1578,665)
  37.  
  38. #Sumbit Close
  39. submitCloseB = (417,560)
  40.  
  41. stockName = "^DJI"
  42. stockURL = "https://markets.businessinsider.com/futures/dow-futures"
  43.  
  44. delay = 0.2
  45.  
  46. stopLoss = 131
  47.  
  48. """
  49. User-setup complete
  50. """
  51.  
  52.  
  53.  
  54. mouse = mo()
  55. keyboard = ke()
  56.  
  57. running = False
  58.  
  59.  
  60.  
  61.  
  62.  
  63. def log_error(e):
  64.     """
  65.     It is always a good idea to log errors.
  66.     This function just prints them, but you can
  67.     make it do anything.
  68.     """
  69.     print(e)
  70.  
  71. def is_good_response(resp):
  72.     """
  73.     Returns true if the response seems to be HTML, false otherwise
  74.     """
  75.     content_type = resp.headers['Content-Type'].lower()
  76.     return (resp.status_code == 200
  77.             and content_type is not None
  78.             and content_type.find('html') > -1)
  79.  
  80.  
  81. def simple_get(url):
  82.     """
  83.     Attempts to get the content at `url` by making an HTTP GET request.
  84.     If the content-type of response is some kind of HTML/XML, return the
  85.     text content, otherwise return None
  86.     """
  87.     try:
  88.         with closing(get(url, stream=True)) as resp:
  89.             if is_good_response(resp):
  90.                 return resp.content
  91.             else:
  92.                 return None
  93.  
  94.     except RequestException as e:
  95.         log_error('Error during requests to {0} : {1}'.format(url, str(e)))
  96.         return None
  97.  
  98.  
  99. def GetCurrentPrice(url):
  100.     raw_html = simple_get(url)
  101.     html = BeautifulSoup(raw_html, "html.parser")
  102.  
  103.     # Getting all span where the class is named "push.-data"
  104.     mydivs = html.findAll("span", {"class": "push-data"})
  105.     temp = str(mydivs[0])
  106.  
  107.     # Getting the first index of where the price is in the string.
  108.     firstIndex = temp.find('">') + 2
  109.  
  110.     # Getting the last index of where the price is in the string.
  111.     lastIndex = temp.find('</span>')  # index before span.
  112.  
  113.     # Getting the price from the string
  114.     price = temp[firstIndex:lastIndex]
  115.  
  116.     # Formating xx,xxx.xx -> xxxxx.xx
  117.     formatted = price.replace(',', '')
  118.  
  119.     return float(formatted)
  120.  
  121.  
  122. #state: Long = True, short = False.
  123. def buyStock(state):
  124.  
  125.     #Universal
  126.     mouse.position = (tradeB[0],tradeB[1])
  127.     time.sleep(delay)
  128.     mouse.click(Button.left)
  129.     time.sleep(delay)
  130.     mouse.click(Button.left)
  131.     time.sleep(delay)
  132.  
  133.  
  134.     if(state == True):
  135.         #Buy
  136.         mouse.position = (buyB[0], buyB[1])
  137.         time.sleep(delay)
  138.         mouse.click(Button.left)
  139.         time.sleep(delay)
  140.  
  141.     elif (state == False):
  142.         #Sell
  143.         mouse.position = (sellB[0], sellB[1])
  144.         time.sleep(delay)
  145.         mouse.click(Button.left)
  146.         time.sleep(delay)
  147.  
  148.     #Click stop / limit
  149.     mouse.position = (stopLossB[0], stopLossB[1])
  150.     time.sleep(delay)
  151.     mouse.click(Button.left)
  152.     time.sleep(delay)
  153.  
  154.     #Ready to type stop loss points.
  155.     mouse.position = (pointsAwayF[0], pointsAwayF[1])
  156.     time.sleep(delay)
  157.     mouse.click(Button.left)
  158.     time.sleep(delay)
  159.     mouse.click(Button.left)
  160.     time.sleep(delay)
  161.  
  162.     #Type 131
  163.     keyboard.type(str(stopLoss))
  164.     time.sleep(delay)
  165.  
  166.     #Submit
  167.     mouse.position = (sumbitB[0], sumbitB[1])
  168.     time.sleep(delay)
  169.     mouse.click(Button.left)
  170.     time.sleep(delay)
  171.  
  172.     #Def done
  173.  
  174. def getYesterdayStockPrice():
  175.     if(datetime.now().weekday() == 0):
  176.         yesterday = date.today() - timedelta(days=2)  # This is indirectly getting fridays stockprice
  177.         temp = yf.download(stockName, yesterday, yesterday)
  178.         return np.array(temp["Close"])[0]
  179.     elif (datetime.now().weekday() > 0 & datetime.now().weekday() <= 4):
  180.         yesterday = date.today()  # This is indirectly getting yesterdays stockprice
  181.         temp = yf.download(stockName, yesterday, yesterday)
  182.         return np.array(temp["Close"])[0]
  183.  
  184. #Run script
  185. def run():
  186.     tstart = GetCurrentPrice(stockURL)
  187.     print("Current stock price: " + str(tstart))
  188.  
  189.     yesterdayStockPrice = getYesterdayStockPrice()
  190.     print("Yesterdays close price: " + str(yesterdayStockPrice))
  191.  
  192.     time.sleep(0.5)
  193.  
  194.     #If todays price is bigger than yesterdays, then buy.
  195.     if(tstart > yesterdayStockPrice):
  196.         buyStock(True)
  197.     elif (tstart < yesterdayStockPrice):
  198.         buyStock(False)
  199.     else:
  200.         print("ERROR, same price yesterday as today.")
  201.  
  202.  
  203. def closePosition():
  204.  
  205.     #Close X
  206.     mouse.position = (closeB[0], closeB[1])
  207.     time.sleep(delay)
  208.     mouse.click(Button.left)
  209.     time.sleep(0.1)
  210.  
  211.     #Close Submit
  212.     mouse.position = (submitCloseB[0], submitCloseB[1])
  213.     time.sleep(delay)
  214.     mouse.click(Button.left)
  215.     time.sleep(delay)
  216.  
  217.     print("Closed position, at: " + str(datetime.now().strftime("%H:%M:%S")))
  218.  
  219. #THE LOOP, which checks if it is weekend, and if not, then gets all the data.
  220. while True:
  221.     if(datetime.now().weekday() >= 0 and datetime.now().weekday() <= 4):
  222.  
  223.         currentTime = datetime.now().strftime("%H:%M:%S")
  224.         print(currentTime)
  225.         if(running == False):
  226.             if (currentTime == "15:29:58"):
  227.                 run()
  228.                 running = True
  229.         elif(running == True):
  230.             if(currentTime == "21:59:58"):
  231.                 closePosition()
  232.                 running = False
  233.  
  234.     else:
  235.         print("WEEKEND")
  236.     time.sleep(1)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top