Esempio n. 1
0
    def __init__(self, proxyPath="./config/proxies.txt", useProxies=True):
        self.proxies = []

        self.currentProxy = 0

        self.useProxies = useProxies

        try:
            with open(proxyPath) as pf:
                for proxy in pf.readlines():
                    self.format(proxy.replace("\n", ""))
        except:
            log("[Error] - Unable to load proxies from file. Please check " + proxyPath)
Esempio n. 2
0
def sendReq(site):
    print(site)
    headers = {
        "X-Shopify-Storefront-Access-Token": site[1],
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0",
        "content-type": "application/json"
    }
    schema1 = SCHEMA.replace("{PRODUCT_CONNECTION}",
                             "first: 250, reverse: false")
    req = requests.post(site[0], json={"query": schema1}, headers=headers)
    print(req.status_code)
    if req.status_code != 200 or "thro" in req.text:
        log("[Fail] - request throttled")
    else:
        log("[Successful] - verified request")
Esempio n. 3
0
 def setFrameRange(self, frame_range):
     """This method sets frame range of slider.
     Args:
         frame_range (list): List contaning start and end frame integers.
     Returns:
         (list): Returns list of Tick items.
     """
     if frame_range[0] <= frame_range[1]:
         logger.log(msg="Setting frame range to [{}-{}]".format(
             frame_range[0], frame_range[1]))
         self.framerange = frame_range
         self.scene.update()
         return self.ticks
     else:
         logger.log(typ="ERROR",
                    msg="Set Frame range Error,"
                    " start frame cannot be greater than end frame")
Esempio n. 4
0
    def onChangeEndField(self):
        """This method sets the frame-range on end field change.
        Returns:
            (None): Returns None.
        """
        start_frame = self.startField.text()
        end_frame = self.endField.text()
        if not start_frame.isdigit() or not end_frame.isdigit():
            logger.log(typ="ERROR", msg="end frame number must be an integer.")
            self.endField.setText(str(self.endFrame))
            return
        if int(end_frame) < int(start_frame):
            logger.log(typ="ERROR",
                       msg="Start frame cannot be greater than end frame")
            self.endField.setText(str(self.endFrame))
            return

        self.setFrameRange([start_frame, end_frame])
Esempio n. 5
0
 def setFrameRange(self, framerange):
     """This method sets frame range of this widget.
     Args:
         framerange (list): List containing start and end frame.
     Returns:
         (None): Returns None.
     """
     if not framerange[0].isdigit()\
             or not framerange[1].isdigit():
         logger.log(typ="ERROR",
                    msg="Frame range must be list of integers {}".format(
                        framerange))
         return
     self.frameRange = [int(framerange[0]), int(framerange[1])]
     self.startFrame = int(framerange[0])
     self.endFrame = int(framerange[1])
     self.duration = (self.endFrame - self.startFrame) + 1
     self.view.scene.slider.setFrameRange(self.frameRange)
Esempio n. 6
0
def getSiteInfo(site):

    siteInfo = {}
    try:
        reqHtml = requests.get(site + "/index.js")
        reqSoup = BS(reqHtml.text, "html.parser")
        siteInfo['apiKey'] = json.loads(
            reqSoup.find("script", {
                'id': 'shopify-features'
            }).text)['accessToken']

        reqMeta = requests.get(site + "/meta.json")
        metaJson = reqMeta.json()
        siteInfo['siteName'] = metaJson['name']
        siteInfo['myShopifyDomain'] = metaJson['myshopify_domain']
        return siteInfo
    except Exception as e:
        log("[Fatal] - Unable to get site info - Site ommited - " + site)
        return {}
Esempio n. 7
0
 def checkTradable(self):  # FUNCTION 6
     log(
         "Please enter the stock you would like to see trade status for. (EX: 'AAPL')",
         3)
     stock = input()
     try:
         checkAsset = self.api.get_asset(stock)  # Grabs stock
         if checkAsset.tradable:
             log(stock + " is tradable.", 1)
         else:
             log(stock + " is not tradable.", 4)
     except:
         log("Error finding " + stock, 2)
Esempio n. 8
0
    def run(self):
        while True:
            for x in range(3):
                if self.scrape():
                    break
                else:
                    time.sleep(.1)

            if self.isBase:
                log('[Success] Finished inital /graphql.json scrape - ' +
                    self.link)
                self.isBase = False
            else:
                log('[Success] Scrape completed - ' + self.link)

            self.proxyNum += 1

            self.sendNotif = True

            time.sleep(MONITOR_SLEEP)
Esempio n. 9
0
    def __init__(self):  # Creates session/logs in
        try:
            self.api = tradeapi.REST(base_url=base_url,
                                     key_id=api_key_id,
                                     secret_key=api_secret)

            self.account = self.api.get_account()
            log("Successfully logged into account.", 1)
            log('${} is available as buying power.'.format(
                self.account.buying_power), 1)  # Checks buying power
        except:
            log("Failed to login to account.", 2)
            quit()
Esempio n. 10
0
 def checkMarket(self):  # FUNCTION 5
     clock = self.api.get_clock()
     log('The market is {}'.format('open.' if clock.is_open else 'closed.'),
         1)  # checks if market is open
Esempio n. 11
0
 def displayPortfolio(self):  # FUNCTION 3
     portfolio = self.api.list_positions()
     for position in portfolio:
         log("{} shares of {}".format(position.qty, position.symbol), 1)
Esempio n. 12
0
    def sellOrder(self):  # FUNCTION 2
        log(
            "Please enter the stock you would like to sell or leave blank to exit.",
            3)
        stock = input()

        if stock != "":
            log("Please enter the number of shares you would like to sell:", 3)
            quantity = input()
            log("Confirming " + str(quantity) + " of " + stock, 3)
            log("Confirm sale? (Y/N)", 3)
            status = input()

            if status == "Y":
                try:
                    self.api.submit_order(  # commit sell order
                        symbol=stock,
                        qty=quantity,
                        side="sell",
                        type="market",
                        time_in_force='gtc')
                    log("Order Submitted.", 1)
                except:
                    log("Failed to submit order.", 2)

            else:
                log("Cancelling order...", 3)

        else:
            log("Exiting menu.", 3)
Esempio n. 13
0
from classes.UserInteraction import UserInteraction
from classes.logger import log
from colorama import Fore

print(
    Fore.CYAN +
    "\n********************* Welcome to Alpaca's User Input Driven Program *********************\n"
)
session = UserInteraction()

while True:
    try:
        print()
        log("Press 1 to purchase equitites", 3)
        log("Press 2 to sell equities", 3)
        log("Press 3 to display portfolio", 3)
        log("Press 4 to display orders", 3)
        log("Press 5 to check if the market is open", 3)
        log("Press 6 to check if a stock is tradable", 3)
        log("Press 7 to list assets on the NASDAQ", 3)
        log("Press 8 to exit", 3)

        choice = int(input())

        if choice == 1:
            session.submitOrder()

        elif choice == 2:
            session.sellOrder()

        elif choice == 3:
Esempio n. 14
0
    def compare(self):
        productId = int(
            b64decode(self.product['id']).decode("utf-8").split("/")[-1:][0])

        if isNew(productId):
            self.productInfo[
                'link'] = self.link + "/products/" + self.product['handle']
            self.productInfo['title'] = self.product['title']

            try:
                currencyBase = CURRENCIES[self.product['priceRange']
                                          ['maxVariantPrice']['currencyCode']]
            except:
                currencyBase = ''

            price = self.product['priceRange']['maxVariantPrice']['amount']
            if price.endswith(".0"):
                self.productInfo['price'] = currencyBase + price + "0"
            else:
                self.productInfo['price'] = currencyBase + price

            self.productInfo['available'] = self.product['availableForSale']

            try:
                self.productInfo['image'] = self.product['images']['edges'][0][
                    'node']['transformedSrc'].replace(
                        "https:\/\/cdn.shopify.com",
                        "https://cdn.shopify.com").replace("\/", "/")
            except:
                self.productInfo[
                    'image'] = "https://www.unesale.com/ProductImages/Large/notfound.png"

            if isFiltered(self.productInfo['title']):
                self.productInfo['filtered'] = True
            else:
                try:
                    t = self.product['variants']['edges'][0]['node'][
                        'title'] + self.product['variants']['edges'][0][
                            'node']['sku']
                except:
                    t = ''
                filterStr = self.productInfo['title'] + str(
                    productId) + self.product['handle'].replace(
                        '-', ' ') + self.productInfo['image'] + self.product[
                            'vendor'] + ''.join(self.product['tags']) + t
                isFilt = isFiltered(filterStr)
                if isFilt:
                    self.productInfo['filtered'] = isFilt
                else:
                    self.productInfo['filtered'] = isFilt

            self.productInfo['variants'] = []

            for var in self.product['variants']['edges']:
                variant = var['node']
                if variant['availableForSale']:
                    varTemp = {}

                    varTemp['id'] = int(
                        b64decode(
                            variant['id']).decode("utf-8").split("/")[-1:][0])
                    varTemp['title'] = variant['title']

                    self.productInfo['variants'].append(varTemp)

            if not self.isBase and self.sendNotif:
                Thread(target=Distribute,
                       args=("New Product", self.link, self.siteName,
                             self.notifGroup),
                       kwargs={
                           "productInfo": self.productInfo
                       }).start()
                log('[Success] Monitor change detected (new) - ' +
                    self.productInfo['link'])

            updateList(productId, self.productInfo)

            # -> TESTING ONLY <- #
            # Thread(target=Distribute, args=("Restock", self.link, self.siteName, self.notifGroup), kwargs={"productInfo": self.productInfo}).start()
            # log('[Success] Monitor change detected (restock) - ' + self.productInfo['link'])
            # -> TESTING ONLY <- #

            return True

        self.productInfo = getCurrentDict(productId)

        newVars = []
        for var in self.product['variants']['edges']:
            variant = var['node']
            if variant['availableForSale']:
                varTemp = {}

                varTemp['id'] = int(
                    b64decode(
                        variant['id']).decode("utf-8").split("/")[-1:][0])
                varTemp['title'] = variant['title']

                newVars.append(varTemp)

        if self.isRestock(newVars):
            if not self.isBase and self.sendNotif:
                Thread(target=Distribute,
                       args=("Restock", self.link, self.siteName,
                             self.notifGroup),
                       kwargs={
                           "productInfo": self.productInfo
                       }).start()
                log('[Success] Monitor change detected (restock) - ' +
                    self.productInfo['link'])

            updateList(productId, self.productInfo)
            return True

        return False
Esempio n. 15
0
    def scrape(self):
        if self.isBase:
            connection = "first: 250, reverse: true, sortKey: UPDATED_AT"
        else:
            connection = """first: 100, reverse: true, sortKey: UPDATED_AT, query: "updated_at:>='{}'" """.format(
                str(self.lastUpdated))

        schema = SCHEMA.replace("{PRODUCT_CONNECTION}", connection)

        if self.isBase or self.proxyNum == PROXY_ROTATION_RATE:
            self.proxyNum = 0
            self.proxy = proxyManager.nextProxy()

        try:
            req = requests.post(self.shopifyDomain + '/api/graphql.json',
                                json={"query": schema},
                                headers=self.headers,
                                proxies=self.proxy)
        except Exception as e:
            log('[Error] Unable to make /graphql.json request - ' + str(e) +
                ' - ' + self.link)
            return False

        if req.status_code == 403 or req.status_code == 430:
            log('[Error] Proxy banned on /graphql.json request!')
            return False

        if req.status_code == 401 or req.status_code == 400:
            if not self.isPasswordUp:
                self.isPasswordUp = True
                if not self.isBase:
                    Thread(target=Distribute,
                           args=("Password Page Up", self.link, self.siteName,
                                 'password')).start()
                    log('Password Page Up - ' + self.link)
            return True

        if self.isPasswordUp:
            self.isPasswordUp = False
            if not self.isBase:
                Thread(target=Distribute,
                       args=("Password Page Down", self.link, self.siteName,
                             'password')).start()
                log('Password Page Down - ' + self.link)
                if not self.sendPassProds:
                    self.sendNotif = False

        if req.status_code == 304:
            pass

        if req.status_code != 200:
            log('[Error] Unknown status code on /graphql.json request - ' +
                str(req.status_code))
            return False

        try:
            self.parse(req.json())
            return True
        except Exception as e:
            log('[Error] Unable to parse /graphql.json sitemap - ' + self.link)
            return False