Exemplo n.º 1
0
def notify(img):
    global botchannel
    global bot_id
    global slack_client
    global RTM_DELAY
    print("Informing User, Initialising Bot....")
    print("Bot Initialised")
    slack_client.api_call(
        "chat.postMessage",
        channel=botchannel,
        text=
        "Hi, Did you send any Guest to your home?.(Yes/No).Please respond immedialtely within 5 min."
    )
    imgbot.sendimage(img)
    if slack_client.rtm_connect(with_team_state=False):
        sent_status = "False"
        bot_id = slack_client.api_call("auth.test")["user_id"]
        while time.time() < t_end:
            cmd, botchannel = parse_bot_cmd(slack_client.rtm_read())
            print(cmd, botchannel)
            if cmd:
                print("in cmd")
                sent_status = "True"
                handle_cmd(cmd, botchannel)
                break
            time.sleep(RTM_DELAY)
        if sent_status == "False":
            print("informing neighbors")
            Notify.notify_neighbor("Bhuvaneshwaran")
            slack_client.api_call(
                "chat.postMessage",
                channel=botchannel,
                text="Didn't get a Response,Informing Neighbors")
    else:
        print("Connection failed.Exception traceback printed above.")
Exemplo n.º 2
0
def sell(asset,sold_price,reason):
    WalletList = wallet.find_one({'asset': asset},sort=[( '_id', DESCENDING )])
    Notify.notify(asset, 'Satış Alarmı', 'ZSim3 Macd', sound=True)
    print("<b><blue>SATILDI</blue> </b>")
    print("<b>{}</b>".format(asset))

    sold.insert_one({
        'asset': asset,
        'sold_price': sold_price,
        'sold_time': datetime.now(),
        'buy_data': WalletList,
        'reason': reason,
        }) 
    wallet.delete_one({'asset': asset})  

    #  Gerçek satış durumunda bakiyeler güncelleniyor

    hotwallet_asset_check = hotwallet.find_one({'asset': asset},sort=[( '_id', DESCENDING )])
    tether_qty_sell = hotwallet_asset_check['qty'] * float(sold_price)
    
    hotwallet_check_for_current_qty = hotwallet.find_one({'asset': 'USDT'},sort=[( '_id', DESCENDING )])
    hotwallet_tether_new_qty = hotwallet_check_for_current_qty['qty'] + tether_qty_sell
            
    condition = { "asset": asset }
    update_data = { "$set": { "qty": 0 } }
    hotwallet.update_one(condition, update_data)

    condition = { "asset": 'USDT' }
    update_data = { "$set": { "qty": hotwallet_tether_new_qty } }
    hotwallet.update_one(condition, update_data)
Exemplo n.º 3
0
    def touch_down(self, x, y, contact, pressure=50):
        touch = self.__trans_xy2(x, y)
        if self.__enable_notify:
            Notify.post_touch(*touch)

        _x, _y = self.__trans_xy(x, y)
        self.__inject_touch_event(TOUCH_TOUCH_DOWN, _x, _y, contact, pressure)
        self.__touch_commit()
Exemplo n.º 4
0
def testNotificationTable():
    configurationFile = open("owners.inp", "r")
    table = Notify.createTable(configurationFile)

    print table

    return
Exemplo n.º 5
0
def wx_pub():
    channel = 'wx_pub'
    extra = {}
    extra['open_id'] = 'o9zpMs5MW2-62GAy5hRrjdYVCktU'
    scharge = datagen.create_charge("true",channel, **extra)
    charge_id = scharge['id']
    content, sign_str = Notify.wx_pub(scharge)
    content['sign'] = (hashlib.md5(sign_str).hexdigest()).upper()
    content_final = {k: v.encode('utf-8') for k, v in content.items()}
    print content_final

    result = Notify.send(True,charge_id, content_final)
    if 'success' in result:
        print 'The paid status of {0} charge {1} had updated successfully'.format(channel, charge_id)
    else:
        print 'Failed during update the paid status of {0} charge {1} '.format(channel, charge_id)

    return charge_id
Exemplo n.º 6
0
    def init(self, serial=None, is_portrait=True, long_edge=None, **kwargs):
        # install dependency
        standalone = kwargs["standalone"] if "standalone" in kwargs else True

        __dir__ = os.path.dirname(os.path.abspath(__file__))
        initializer = Initializer(resource_dir=os.path.join(__dir__, ".."))
        initializer.setup(standalone)

        # start touch thread
        self.__touch_handler = TouchSocketHandler(self.__host, self.__touch_port)
        self.__touch_handler.start()
        logger.info("wait touch thread start")
        self.__touch_handler.event.wait()
        logger.info("touch thread started")

        # start cloudscreen thread
        self.__cloudscreen_handler = CloudscreenSocketHandler(self.__host, self.__cloudscreen_port)
        self.__cloudscreen_handler.start()
        logger.info("wait cloudscreen thread start")
        self.__cloudscreen_handler.event.wait()
        logger.info("cloudscreen thread started")

        ret, desc = self.get_device_info()
        if ret is None:
            logger.error("cannot get device info: {}".format(desc))
            return False, desc

        self.__scale = long_edge * 1.0 / self.__deviceInfo.display_height

        if is_portrait:
            self.__game_width = self.__deviceInfo.display_width * self.__scale
            self.__game_height = long_edge
        else:
            self.__game_width = long_edge
            self.__game_height = self.__deviceInfo.display_width * self.__scale
        self.__regular_height = long_edge

        logger.info("game_width={}, height={}".format(self.__game_width, self.__game_height))

        self.__enable_notify = kwargs["enable_notify"] if "enable_notify" in kwargs else False
        if self.__enable_notify:
            logger.info("PlatformWeTest: start Notify thread")
            Notify.start()
        return True, ""
Exemplo n.º 7
0
    def save_dlpath(self, fs, path):
        if not path:
            return

        if not os.path.exists(self.dlsel.path):
            p = Notify.Error(
                self, "Invalid storage path",
                "You have selected an invalid data storage path for torrents.")
            return

        self.path_lbl.text = path
        self.conf.set("Settings", "storage_path", self.dlsel.path)
Exemplo n.º 8
0
def handle_cmd(cmd, channel):
    global slack_client
    print("Handling Command")
    default_msg = "Response is Not Valid.Please enter a valid response.Enter*{}*.".format(
        response_text)

    response = None

    if cmd.lower() == "yes":
        print("User Responded Yes")
        response = "OK.I will turn on the Guest mode for them."
        db.fetch("Guest", None)
    elif cmd.lower() == "no":
        print("User Responded No")
        response = "OK.I will inform the Neighbors."
        Notify.notify_neighbor("Bhuvaneshwaran")

    slack_client.api_call("chat.postMessage",
                          channel=botchannel,
                          text=response or default_msg)
    print("Handling Complete")
Exemplo n.º 9
0
def alipay():
    # for alipay
    key = load_privatekey(FILETYPE_PEM, open("./External/alipay/rsa_private_key.pem").read())

    # 默认是返回已存在的charge对象;若需要新生成charge,写为: DataGen.GetCharge(channel, True)
    scharge = datagen.create_charge(True,'alipay')
    charge_id = scharge['id']
    content, sign_str = Notify.alipay(scharge)

    sign_charge = sign(key, sign_str, 'sha1')

    ############### verify the signature to ensure the pair without any issues###########

    # pem = open("External/alipay/rsa_public_key.pem").read()
    #
    # bio = BIO.MemoryBuffer(pem)
    # rsa = RSA.load_pub_key_bio(bio)
    # pubkey = EVP.PKey()
    # pubkey.assign_rsa(rsa)
    #
    # pubkey.reset_context(md='sha1')
    # pubkey.verify_init()
    # pubkey.verify_update(sign_str)
    # print pubkey.verify_final(sign_charge)

    #########################################################################################

    sign_final = base64.b64encode(sign_charge)
    content['sign_type'] = "RSA"
    content['sign'] = sign_final
    content_final = {k: v.encode('utf-8') for k, v in content.items()}
    print content_final
    result = Notify.send("true",charge_id, content_final)
    if result == 'success':
        print 'The paid status of alipay charge {0} had updated successfully'.format(charge_id)
        return charge_id,"success"
    else:
        print 'Failed during update the paid status of alipay charge {0} '.format(charge_id)
        return charge_id,"Fail"
	def notify_changes(self, origin):
		try:
			with open(origin) as f:
				comparison = json.load(f)
			for cls, quarters in self.data.items():
				for quarter, sections in quarters.items():
					for section, data in sections.items():
						if len(data['secondaries']) > 0:
							for secondary_id, secondaries in data['secondaries'].items():
								secondary_enrollment = secondaries[0]['enrollment']
								compare_enrollment = comparison[cls][quarter][section]['secondaries'][secondary_id][0]['enrollment']
								if secondary_enrollment != compare_enrollment:
									Notify.emit(quarter, cls, section, secondary_id, compare_enrollment, secondary_enrollment, newest=False)
									print('Update occurred for %s %s %s %s' % (cls, quarter, section, secondary_id))
						else:
							primary_enrollment = data['primaries'][0]['enrollment']
							compare_enrollment = comparison[cls][quarter][section]['primaries'][0]['enrollment']
							if primary_enrollment != compare_enrollment:
								Notify.emit(quarter, cls, section, None, compare_enrollment, primary_enrollment, newest=False)
								print('Update occurred for %s %s %s' % (cls, quarter, section))
		except Exception as e:
			print(e)
Exemplo n.º 11
0
def do(asset):
    result = PMAX(getCandles(asset))

    isInWallet = bought.find_one({'asset': asset}, sort=[('_id', DESCENDING)])

    current_pmax = result['pmX_4_0.1_4_7'][499]
    last_pmax = result['pmX_4_0.1_4_7'][498]

    if (last_pmax != current_pmax):
        if (current_pmax == "down"):
            if (isInWallet != None):
                print("<b><blue>SATILDI</blue> </b>")
                print("<b>{}</b>".format(asset))
                print("<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>".format(
                    result))
                sold.insert_one({
                    'asset': asset,
                    'pmax': result['pmX_4_0.1_4_7'][499],
                    'sold_price': result['close'][499],
                    'buy_data': isInWallet,
                    'sold_time': datetime.now()
                })
                bought.delete_one({'asset': asset})
        else:
            if (isInWallet == None):
                Notify.notify(asset, 'Alım Sinyali', 'Trader V1', sound=True)
                print("<b><blue>SATIN ALINDI</blue> </b>")
                print("<b>{}</b>".format(asset))
                print("<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>".format(
                    result))
                bought.insert_one({
                    'asset': asset,
                    'pmax': result['pmX_4_0.1_4_7'][499],
                    'buy_price': result['close'][499],
                    'buy_time': datetime.now()
                })
            else:
                print("<b><green>Pmax Up Uyarısı</green> <red>Tekrar</red>")
                print("<b>{}</b>".format(asset))
Exemplo n.º 12
0
 def run(self):
     GPIO.setmode(GPIO.BCM)
     global intruder
     SR = 14
     KITCHEN = 18
     BEDROOM = 23
     PORCH = 24
     PORCH_MOTION = 25
     GPIO.setup(SR, GPIO.IN)
     GPIO.setup(KITCHEN, GPIO.IN)
     GPIO.setup(BEDROOM, GPIO.IN)
     GPIO.setup(PORCH, GPIO.IN)
     GPIO.setup(PORCH_MOTION, GPIO.IN)
     try:
         time.sleep(2)
         while self._running:
             intruder = None
             if not GPIO.input(PORCH_MOTION) and GPIO.input(PORCH):
                 print("Porch")
                 intruder = "Porch"
             if GPIO.input(SR):
                 print("Store Room")
                 intruder = "Store Room"
             if not GPIO.input(KITCHEN):
                 print("Kitchen")
                 intruder = "Kitchen"
             if not GPIO.input(BEDROOM):
                 intruder = "Bedroom"
                 print("Bedroom")
             if intruder is not None:
                 notify.notify_neighbor("Bhuvaneshwaran")
                 notify.notifyuser_place(intruder)
                 sleep(5)
     except KeyboardInterrupt:
         print("Quit")
         GPIO.cleanup()
Exemplo n.º 13
0
    def apply_settings(self, btn, widgets, session):
        s = lt.session_settings()

        for k, w in widgets.iteritems():

            if k == "disk_cache_algorithm":
                v = lt.disk_cache_algo_t(w.value)
            elif isinstance(w, Spinner):
                v = int(w.value)
            elif isinstance(w, Slider):
                v = w.value
            elif isinstance(w, Entry):
                v = w.entry.encode("utf-8")
            elif isinstance(w, Check):
                v = bool(w.state)
            else:
                v = None

            setattr(s, k, v)

        session.set_settings(s)
        Notify.Information(self, "Session settings saved.")
Exemplo n.º 14
0
        ff = ffmpy.FFmpeg(inputs={'temp.ogg': None},
                          outputs={'temp.flac': None})
        ff.run()

        # The name of the audio file to transcribe
        file_name = os.path.join(os.path.dirname(__file__), 'temp.flac')
        print("Performing SpeechToText Analysis")
        word_list, confidence = SpeechToText.speech_to_text(file_name)
        location_trigger, keywords = NLP.check_for_location(
            word_list, KEYWORDS)  # type: (bool, List[Any])

        if location_trigger is True:
            print("Keywords Detected: Sending Alert for Keyword(s): " +
                  str(keywords) + " Confidence = " +
                  "{0:.2f}".format(confidence))
            Notify.text_alert(word_list, keywords, confidence)

        os.remove("temp.flac")
        print("No keywords detected")
        time.sleep(35)
        s.terminate()
        s.join()

        print("Converting to FLAC")
        ff = ffmpy.FFmpeg(inputs={'temp.ogg': None},
                          outputs={'temp.flac': None})
        ff.run()

        # The name of the audio file to transcribe
        file_name = os.path.join(os.path.dirname(__file__), 'temp.flac')
        print("Performing SpeechToText Analysis")
Exemplo n.º 15
0
def do(asset):

    walletAssets()

    # sys.stdout.write(asset)

    result = PMAX(getCandles(asset))

    WatchList = track.find_one({'asset': asset}, sort=[('_id', DESCENDING)])
    WalletList = wallet.find_one({'asset': asset}, sort=[('_id', DESCENDING)])

    current_pmax = result['pmX_4_0.1_4_7'][len(result) - 1]
    last_pmax = result['pmX_4_0.1_4_7'][len(result) - 2]

    index = 0
    numpy_data = []
    while index <= 5:
        numpy_data.append({
            'open':
            result['open'][index + (len(result) - 6)],
            'high':
            result['high'][index + (len(result) - 6)],
            'low':
            result['low'][index + (len(result) - 6)],
            'close':
            result['close'][index + (len(result) - 6)],
            'volume':
            result['volume'][index + (len(result) - 6)],
            'ATR_4':
            result['ATR_4'][index + (len(result) - 6)],
            'MA_7_4':
            result['MA_7_4'][index + (len(result) - 6)],
            'pm_4_0_1_4_7':
            result['pm_4_0.1_4_7'][index + (len(result) - 6)],
            'pmX_4_0_1_4_7':
            result['pmX_4_0.1_4_7'][index + (len(result) - 6)],
        })
        index += 1

    # Eğer Watchlist elemanı negatif değere düştüyse listeden çıkar
    if (WatchList != None):  # İzleme Listesindeyse
        time.sleep(1)

        try:
            candles = client.get_all_tickers()
        except:
            time.sleep(30)
            candles = client.get_all_tickers()
            pass

        buy_price = float(WatchList['buy_price'])
        for candle in candles:
            if (candle['symbol'] == asset):
                current_price = float(candle['price'])
                if (current_price < buy_price):
                    track.delete_one({'asset': asset})
                    print(
                        "<b><blue>Fiyat düştüğü için izleme listesinden çıkarıldı</blue> </b>"
                    )
                    print("<b>{}</b>".format(asset))

    # Satış kontrolü,  fiyat ortalaması son fiyatın altına düşerse sat
    if (WalletList != None):  # Cüzdandaysa
        time.sleep(1)
        Prices = client.get_all_tickers()
        for price in Prices:
            if (price['symbol'] == asset):
                current_price = float(price['price'])

                # updated_price_new_array=[]
                # updated_price_new_array.append(current_price)

                # condition = { "asset": asset }
                # update_data = { "$set": { "updated_price": updated_price_new_array } }
                # wallet.update_one(condition, update_data)

                _buy_price = float(WalletList['buy_price'])
                _percentage = (
                    (current_price - _buy_price) / current_price) * 100

                # %5 kâr olmadığı sürece elde tut
                if (_percentage > 3):
                    try:
                        if (WalletList['updated_price'] != 0):
                            updated_price_new_array = []
                            wallet_updated_price = WalletList['updated_price']
                            total_wallet_updated_price = 0
                            for u_price in wallet_updated_price:
                                updated_price_new_array.append(float(u_price))
                                total_wallet_updated_price += float(u_price)

                            updated_price_new_array.append(current_price)
                            total_wallet_updated_price += current_price

                            average_of_updated_prices = total_wallet_updated_price / len(
                                updated_price_new_array)
                            last_updated_price = updated_price_new_array[
                                len(updated_price_new_array) - 1]

                            print(
                                "<b><red>average_of_updated_prices</red> </b><b><yellow>{}</yellow></b>"
                                .format(average_of_updated_prices))
                            print(
                                "<b><red>last_updated_price</red> </b><b><yellow>{}</yellow></b>"
                                .format(last_updated_price))

                            if len(updated_price_new_array) >= 5:
                                print('len(updated_price_new_array)',
                                      len(updated_price_new_array))
                                # if (average_of_updated_prices - ((average_of_updated_prices/100)*20) > last_updated_price):
                                if (average_of_updated_prices >
                                        last_updated_price):
                                    condition = {"asset": asset}
                                    update_data = {
                                        "$set": {
                                            "updated_price":
                                            updated_price_new_array
                                        }
                                    }
                                    wallet.update_one(condition, update_data)
                                else:
                                    Notify.notify(asset,
                                                  'Satış Alarmı - Ortalama',
                                                  'Trader Sim - 1',
                                                  sound=True)
                                    print("<b><blue>SATILDI</blue> </b>")
                                    print("<b><green>Ortalama düştü</green>")
                                    print("<b>{}</b>".format(asset))

                                    # Silinecek

                                    WatchList = track.find_one(
                                        {'asset': asset},
                                        sort=[('_id', DESCENDING)])
                                    WalletList = wallet.find_one(
                                        {'asset': asset},
                                        sort=[('_id', DESCENDING)])

                                    # print('WalletList', WalletList)
                                    # print('Watchlist', WatchList)

                                    # Notify.notify(asset, 'SATIŞ', 'Trader V2', sound=True)

                                    # Silinecek

                                    sold.insert_one({
                                        'asset':
                                        asset,
                                        'pmax':
                                        result['pmX_4_0.1_4_7'][len(result) -
                                                                1],
                                        'sold_price':
                                        result['close'][len(result) - 1],
                                        'buy_data':
                                        WalletList,
                                        'sold_time':
                                        datetime.now(),
                                        'candle_data':
                                        numpy_data,
                                        'reason':
                                        'Ortalama',
                                    })
                                    wallet.delete_one({'asset': asset})

                                    #  Gerçek satış durumunda bakiyeler güncelleniyor
                                    hotwallet_check = hotwallet.find_one(
                                        {'asset': 'USDT'},
                                        sort=[('_id', DESCENDING)])
                                    available = hotwallet_check['qty']

                                    hotwallet_asset_check = hotwallet.find_one(
                                        {'asset': asset},
                                        sort=[('_id', DESCENDING)])
                                    tether_qty_sell = hotwallet_asset_check[
                                        'qty'] * float(
                                            result['close'][len(result) - 1])

                                    hotwallet_check_for_current_qty = hotwallet.find_one(
                                        {'asset': 'USDT'},
                                        sort=[('_id', DESCENDING)])

                                    hotwallet_tether_new_qty = hotwallet_check_for_current_qty[
                                        'qty'] + tether_qty_sell

                                    condition = {"asset": asset}
                                    update_data = {"$set": {"qty": 0}}
                                    hotwallet.update_one(
                                        condition, update_data)

                                    condition = {"asset": 'USDT'}
                                    update_data = {
                                        "$set": {
                                            "qty": hotwallet_tether_new_qty
                                        }
                                    }
                                    hotwallet.update_one(
                                        condition, update_data)

                    except:
                        updated_price_init = []

                        try:
                            updated_price_init.append(current_price)
                        except:
                            updated_price_init.append(0)
                            pass
                        condition = {"asset": asset}
                        update_data = {
                            "$set": {
                                "updated_price": updated_price_init
                            }
                        }
                        wallet.update_one(condition, update_data)
                        pass

    # Eğer artık Pmax geçerli değilse watchlistten çıkar
    if (last_pmax == current_pmax):
        if (WatchList != None):
            track.delete_one({'asset': asset})
            print(
                "<b><green>Pmax geçerli değil, izleme listesinden çıkarıldı</green>"
            )

    if (last_pmax != current_pmax):
        # Satış mantığı, fiyat Pmax'e göre düşüşteyse sat. Bu kısım zarara girmeden satış yapamadı
        if (current_pmax == "down"):
            if (WalletList != None):  # Cüzdanda ise

                time.sleep(1)
                Prices = client.get_all_tickers()
                for price in Prices:
                    if (price['symbol'] == asset):
                        current_price = float(price['price'])

                _buy_price = float(WalletList['buy_price'])
                _percentage = (
                    (current_price - _buy_price) / current_price) * 100

                # %5 kâr olmadığı sürece elde tut
                if (_percentage > 3):
                    Notify.notify(asset,
                                  'Satış Alarmı - Pmax',
                                  'Trader Sim - 1',
                                  sound=True)
                    print("<b><blue>SATILDI</blue> </b>")
                    print("<b><green>Pmax Sinyali</green>")
                    print("<b>{}</b>".format(asset))

                    # Silinecek
                    WatchList = track.find_one({'asset': asset},
                                               sort=[('_id', DESCENDING)])
                    WalletList = wallet.find_one({'asset': asset},
                                                 sort=[('_id', DESCENDING)])

                    # print('WalletList', WalletList)
                    # print('Watchlist', WatchList)

                    # Silinecek

                    sold.insert_one({
                        'asset':
                        asset,
                        'pmax':
                        result['pmX_4_0.1_4_7'][len(result) - 1],
                        'sold_price':
                        result['close'][len(result) - 1],
                        'buy_data':
                        WalletList,
                        'sold_time':
                        datetime.now(),
                        'candle_data':
                        numpy_data,
                        'reason':
                        'Pmax',
                    })
                    wallet.delete_one({'asset': asset})

                    #  Gerçek satış durumunda bakiyeler güncelleniyor
                    hotwallet_check = hotwallet.find_one({'asset': 'USDT'},
                                                         sort=[('_id',
                                                                DESCENDING)])
                    available = hotwallet_check['qty']

                    hotwallet_asset_check = hotwallet.find_one(
                        {'asset': asset}, sort=[('_id', DESCENDING)])
                    tether_qty_sell = hotwallet_asset_check['qty'] * float(
                        result['close'][len(result) - 1])

                    hotwallet_check_for_current_qty = hotwallet.find_one(
                        {'asset': 'USDT'}, sort=[('_id', DESCENDING)])

                    hotwallet_tether_new_qty = hotwallet_check_for_current_qty[
                        'qty'] + tether_qty_sell

                    condition = {"asset": asset}
                    update_data = {"$set": {"qty": 0}}
                    hotwallet.update_one(condition, update_data)

                    condition = {"asset": 'USDT'}
                    update_data = {"$set": {"qty": hotwallet_tether_new_qty}}
                    hotwallet.update_one(condition, update_data)

        else:
            #  UP ise
            if (WatchList == None):  # Takip listesinde değilse
                if (WalletList == None):  # Cüzdanda değilse
                    # Notify.notify(asset, 'WatchList Aktif', 'Trader V2', sound=True)

                    print("<b><green>Takip Listesine Alındı</green> </b>")
                    print("<b>{}</b>".format(asset))
                    # print("<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>".format(result) )

                    track.insert_one({
                        'asset':
                        asset,
                        'pmax':
                        result['pmX_4_0.1_4_7'][len(result) - 1],
                        'buy_price':
                        result['close'][len(result) - 1],
                        'buy_time':
                        datetime.now(),
                        'candle_data':
                        numpy_data,
                    })
            else:  # Takip listesindeyse
                if (WalletList == None):  # Cüzdanda değilse
                    time.sleep(1)
                    try:
                        candles = client.get_all_tickers()
                    except:
                        time.sleep(30)
                        candles = client.get_all_tickers()
                        pass

                    for candle in candles:
                        if (candle['symbol'] == asset):
                            current_price = float(candle['price'])
                    buy_price = WatchList['buy_price']
                    percentage = (
                        (current_price - buy_price) / current_price) * 100
                    if (percentage >= 2):

                        # # 1 günlük ve 15 dakikalık check
                        # time.sleep(1)
                        # result1Day = PMAX(getCandles1Day(asset))
                        # time.sleep(1)
                        # result15Min = PMAX(getCandles15Min(asset))
                        # current_pmax_1Day = result1Day['pmX_4_0.1_4_7'][len(result1Day)-5],result1Day['pmX_4_0.1_4_7'][len(result1Day)-4],result1Day['pmX_4_0.1_4_7'][len(result1Day)-3],result1Day['pmX_4_0.1_4_7'][len(result1Day)-2],result1Day['pmX_4_0.1_4_7'][len(result1Day)-1]
                        # current_pmax_15Min = result15Min['pmX_4_0.1_4_7'][len(result15Min)-5],result15Min['pmX_4_0.1_4_7'][len(result15Min)-4],result15Min['pmX_4_0.1_4_7'][len(result15Min)-3],result15Min['pmX_4_0.1_4_7'][len(result15Min)-2],result15Min['pmX_4_0.1_4_7'][len(result15Min)-1]

                        # 1 günlük ve 15 dakikalık UP durumunda alım yapılır
                        # if result1Day['pmX_4_0.1_4_7'][len(result1Day)-2] == 'down' and result1Day['pmX_4_0.1_4_7'][len(result1Day)-1] == 'up':
                        # if result15Min['pmX_4_0.1_4_7'][len(result15Min)-2] == 'down' and result15Min['pmX_4_0.1_4_7'][len(result15Min)-1] == 'up':
                        # Notify.notify(asset, 'Alım Sinyali %3', 'Trader V2', sound=True)

                        # Bakiye kontrol ediliyor

                        hotwallet_check = hotwallet.find_one({'asset': 'USDT'},
                                                             sort=[('_id',
                                                                    DESCENDING)
                                                                   ])
                        available = hotwallet_check['qty']

                        if available > per:
                            # Notify.notify(asset, 'Alım Sinyali - 1 D Pmax', 'Trader Sim - 1', sound=True)
                            print(
                                "<b><blue>SATIN ALINDI 1 D Pmax </blue> </b>")
                            print("<b>{}</b>".format(asset))
                            print(
                                "<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>"
                                .format(result))
                            wallet.insert_one({
                                'asset': asset,
                                'buy_price': current_price,
                                'buy_time': datetime.now(),
                                'track_data': WatchList,
                                # 'candle_data': numpy_data,
                                # 'current_pmax_1Day': current_pmax_1Day,
                                # 'current_pmax_15Min': current_pmax_15Min
                            })
                            track.delete_one({'asset': asset})

                            # Gerçek alım durumunda bakiyeler güncelleniyor
                            qty_buy = per / current_price

                            hotwallet_asset_check = hotwallet.find_one(
                                {'asset': asset}, sort=[('_id', DESCENDING)])

                            if (hotwallet_asset_check != None):

                                hotwallet_new_qty = hotwallet_asset_check[
                                    'qty'] + qty_buy

                                condition = {"asset": asset}
                                update_data = {
                                    "$set": {
                                        "qty": hotwallet_new_qty
                                    }
                                }
                                hotwallet.update_one(condition, update_data)
                            else:
                                hotwallet.insert_one({
                                    'asset': asset,
                                    'qty': qty_buy,
                                })

                            hotwallet_check_for_current_qty = hotwallet.find_one(
                                {'asset': 'USDT'}, sort=[('_id', DESCENDING)])

                            hotwallet_tether_new_qty = hotwallet_check_for_current_qty[
                                'qty'] - per

                            condition = {"asset": 'USDT'}
                            update_data = {
                                "$set": {
                                    "qty": hotwallet_tether_new_qty
                                }
                            }
                            hotwallet.update_one(condition, update_data)
                        else:
                            print('Kota dolu')
Exemplo n.º 16
0
    while True:  # Infinite loop
        dt = tNext - datetime.datetime.now()
        if dt > datetime.timedelta(seconds=0):
            msg = 'Sleeping till {}'.format(tNext)
            logger.info(msg)
            db.updateState(myName, msg)
            db.close()  # Should be a while before I'm needed again
            reply = listener.fetch(dt.total_seconds())
            if reply:  # Run triggered by notification
                logger.info("Woke up due to notification(s), %s",
                            prettyWoke(reply, db))
                db.updateState(myName,
                               'Starting notification {}'.format(reply))
            else:  # Run triggered by timeout
                db.updateState(myName, 'Starting')
        logger.info('Starting scheduler run')
        runScheduler(args, logger)
        db.updateState(myName, 'Done')
        if args.single: break  # Break out of loop if only to be done once
        # Just after midnight
        tNext = datetime.datetime.combine(
            datetime.date.today() + datetime.timedelta(days=1),
            datetime.time(0, 0, 1))
    db.updateState(myName, 'Exiting')

except Exception as e:
    logger.exception('Unexpected exception')
    db = DB.DB(args.db, logger)
    db.updateState(myName, repr(e))
    Notify.onException(args, logger)
Exemplo n.º 17
0
def send(sender, message, style=""):
	Notify.Notify(sender, message, style)
	open("c:\\bin\\video_mes.txt", "a+").write("\nFrom: %s\nMessage:\n\t%s\n===="%(sender, message))
Exemplo n.º 18
0
#import libraries
import shopify, requests, json, math, time
from datetime import datetime
import Notify

mailSubject = "WholesaleBox Job Run Started at Server : " + datetime.now(
).strftime('%d-%m-%Y %H:%M:%S')
mailBody = "WholesaleBox Job Run Started at Server: " + datetime.now(
).strftime('%d-%m-%Y %H:%M:%S')

Notify.sendMail(mailSubject, mailBody)

#ratoon shop authentication url
shop_url = "https://*****:*****@ratoon-istore.myshopify.com/admin"

#getting product count
urlToGetProductCount = "https://*****:*****@ratoon-istore.myshopify.com/admin/products/count.json?vendor=Wholesalebox"
urlToGetProductCount_Response = requests.get(urlToGetProductCount)
productCount_Json = json.loads(urlToGetProductCount_Response.content)
totalProductCount = int(productCount_Json['count'])

#setting product limit
productLimit = 50

#total pages available
totalpage = int(math.ceil(totalProductCount / productLimit)) + 1

#Setting our shop
shopify.ShopifyResource.set_site(shop_url)
shop = shopify.Shop.current()
Exemplo n.º 19
0
    def __init__(self):
        gobject.GObject.__init__(self)
        self._device_manager = FreeDesktop.DeviceManager()
        self.conf = Config.Config(tgcm.country_support)
        self.notify = Notify.Notify()
        self.__updater = TrafficUpdater.TrafficUpdater()
        self.__main_modem = FreeDesktop.MainModem.MainModem()
        self.__main_wifi = FreeDesktop.MainWifi.MainWifi()

        # FIXME: Usually it is a bad idea to have a dependency to a UI element in the Core
        self.__dock = tgcm.ui.ThemedDock()

        #TrafficHistoryGraphData
        db_file = os.path.join(tgcm.config_dir,
                               "traffic-%s.db" % tgcm.country_support)
        self._storage = TrafficStorage.TrafficStorage(self.conf, db_file)

        self.is_roaming = None

        # Billing period related expenses
        self._cached_expenses = {}
        self._cached_monthly_limit = {}
        self._cached_billing_period = None

        # Session related expenses
        self.session_data_transfered = 0
        self.session_max_speed = 0

        # Various
        self.last_received_bytes = 0
        self.last_sent_bytes = 0
        self.__monitoring = self.MONITORING_IDLE

        ## Check if a billing period has expired between now and the latest execution ##
        # The only thing necessary that needs to be reset is the SMS counters, because
        # unlike the traffic accounting, it is saved in a incremental register in GConf.
        if self.conf.is_last_imsi_seen_valid():
            imsi = self.conf.get_last_imsi_seen()
            billing_period = self.conf.get_imsi_based_billing_period(imsi)

            # The billing period is a list of Date objects, and the last execution is a
            # Datetime object. In order to compare them, it is necessary to convert the
            # first date of the billing period from Date to Datetime
            last_execution = self.conf.get_last_execution_datetime()
            first_day_period = datetime.datetime.combine(
                billing_period[0], datetime.time())

            # If the date time of the last execution is older than the date of the first
            # day of current billing period, I assume that there have been a billing period
            # change and it is necessary to reset the SMS counters
            if last_execution < first_day_period:
                self.__reset_sms_counters(imsi)

        # Configure current traffic history
        self.__billing_period_change_event = None
        self.__start_traffic_history()

        # Create alert list for current recognized IMSI
        self.__create_current_alerts()

        # -- Signals from the MainModem for detecting the connected/disconnected signals
        self.__main_modem.connect('main-modem-connected',
                                  self.__main_modem_connected_cb)
        self.__main_modem.connect('main-modem-disconnected',
                                  self.__main_modem_disconnected_cb)
        self.__main_wifi.connect('main-wifi-connected',
                                 self.__main_wifi_connected_cb)
        self.__main_wifi.connect('main-wifi-disconnected',
                                 self.__main_wifi_disconnected_cb)

        self.__updater.connect("traffic-updater-trigger",
                               self.__traffic_updater_trigger_cb)

        self.conf.connect('last-imsi-seen-changed',
                          self.__on_last_imsi_changed)
        self.conf.connect('billing-day-changed', self.__on_billing_day_changed)
        self.conf.connect('monthly-limit-changed',
                          self.__on_monthly_limit_changed)
        self.conf.connect('alerts-info-changed', self.__on_alerts_changed)
        self.__dock.connect('app-closing', self.__on_app_close)

        # -- Start the thread that will update the session time
        self.__session_time_event = threading.Event()
        self.__session_time_state = self.SESSION_TIME_INIT
        thread.start_new_thread(self.__session_time_thread, ())
        glib.idle_add(self.__init)
Exemplo n.º 20
0
    def run(self):

        page = WebPage(mainHtmlPage)

        # first extract examples from the repository
        if not options.keep_data:
            rep = Repository()
            Test.extracting = True
            page.output()
            rep.checkout()
            Test.extracting = False

        testinfoPattern = re.compile(r'^[\s\t]*(.+)[\s\t]*<[\s\t]*(.+)[\s\t]*>[\s\t]*([\w\.\d\-\_]+)[\s\t]*,?[\s\t]*'+\
                                     '(subdirectory=)?[\s\t]*(.*)[\s\t]*$')
        # e.g. ./madx < touschek.lhcinjection.madx >  touschek.lhcinjection.out, subdirectory=LHC_injection
        # or ./madx < lep.madx  >  lep.out

        # process TestScenario.xml
        os.system('xsltproc --stringparam what list_targets ProcessScenario.xsl'+\
                  ' TestScenario.xml > ./outfile')
        f = open('./outfile', 'r')
        targets = f.readlines()
        for i, target in enumerate(targets):
            targets[i] = target.strip('\n')
        f.close()
        os.remove('./outfile')

        if options.singleTarget:
            if not options.singleTarget in targets:
                raise ("specified target '" + options.singleTarget +
                       "' does not exists in " + str(targets))

        for target in targets:

            #target = target.rstrip('\n')

            if options.omit:
                if target == options.omit:
                    if options.verbose:
                        print("skip " + options.omit)
                    continue

            if options.singleTarget and not options.singleTarget == target:
                continue  # skip this test

            # extract detailed information about each test
            os.system('xsltproc --stringparam what list_tests'+\
                      ' --stringparam target '+target+\
                      ' ProcessScenario.xsl TestScenario.xml > ./outfile')
            f = open('./outfile', 'r')
            testinfos = f.readlines()
            f.close()
            os.remove('./outfile')
            if options.singleCase:
                recognizedSingleCase = False  # default, must be set to True if valid
            for testinfo in testinfos:
                testinfo = testinfo.rstrip('\n')

                m = testinfoPattern.match(testinfo)
                if m:
                    program = m.group(1).rstrip()
                    input = m.group(2).rstrip()
                    output = m.group(3).rstrip()
                    if m.lastindex == 5:
                        subdirectory = m.group(5)
                    else:
                        subdirectory = 0

                    if options.singleCase and not options.singleCase == input:
                        continue
                    elif options.singleCase and options.singleCase == input:
                        recognizedSingleCase = True

                    test = Test(target, program, input, output, subdirectory)

                else:
                    if options.verbose:
                        print("failed to parse line " + testinfo)

        if options.singleCase and not recognizedSingleCase:
            raise ("specified single case '" + options.singleCase +
                   "' does not exist.")

        try:
            shutil.rmtree(testingDir)
        except:
            pass  # directory absent

        page.output()  # refresh the web page

        # now populate testingDir with all sources and associated resources
        for t in Test.tests:
            t.copyResourcesToTestingDir()

        # now run the tests
        for t in Test.tests:

            t.state = running
            page.output()  # to mark the current test as running
            t.run()
            t.compareOutputWithReference()
            t.state = completed  # or aborted?
            page.output()  # refresh the web page

        # notify module keepers if required
        if options.mail:
            Notify.notify("jean-luc", "test completion",
                          "test completed.")  # for the time-being

            page.output()  # refresh the web page for the last time
Exemplo n.º 21
0
def do(asset):

    # sys.stdout.write(asset)

    result = PMAX(getCandles(asset))

    WatchList = track.find_one({'asset': asset}, sort=[('_id', DESCENDING)])
    WalletList = wallet.find_one({'asset': asset}, sort=[('_id', DESCENDING)])

    current_pmax = result['pmX_4_0.1_4_7'][len(result) - 1]
    last_pmax = result['pmX_4_0.1_4_7'][len(result) - 2]

    index = 0
    numpy_data = []
    while index <= 5:
        numpy_data.append({
            'open':
            result['open'][index + (len(result) - 6)],
            'high':
            result['high'][index + (len(result) - 6)],
            'low':
            result['low'][index + (len(result) - 6)],
            'close':
            result['close'][index + (len(result) - 6)],
            'volume':
            result['volume'][index + (len(result) - 6)],
            'ATR_4':
            result['ATR_4'][index + (len(result) - 6)],
            'MA_7_4':
            result['MA_7_4'][index + (len(result) - 6)],
            'pm_4_0_1_4_7':
            result['pm_4_0.1_4_7'][index + (len(result) - 6)],
            'pmX_4_0_1_4_7':
            result['pmX_4_0.1_4_7'][index + (len(result) - 6)],
        })
        index += 1

    # Eğer Watchlist elemanı negatif değere düştüyse listeden çıkar
    if (WatchList != None):  # İzleme Listesindeyse
        time.sleep(1)

        try:
            candles = client.get_all_tickers()
        except:
            time.sleep(30)
            candles = client.get_all_tickers()
            pass

        buy_price = float(WatchList['buy_price'])
        for candle in candles:
            if (candle['symbol'] == asset):
                current_price = float(candle['price'])
                if (current_price < buy_price):
                    track.delete_one({'asset': asset})
                    print(
                        "<b><blue>Fiyat düştüğü için izleme listesinden çıkarıldı</blue> </b>"
                    )
                    print("<b>{}</b>".format(asset))

    if (last_pmax != current_pmax):
        # Satış mantığı, fiyat Pmax'e göre düşüşteyse sat. Bu kısım zarara girmeden satış yapamadı
        if (current_pmax == "down"):
            if (WalletList != None):  # Cüzdanda ise

                time.sleep(1)
                Prices = client.get_all_tickers()
                for price in Prices:
                    if (price['symbol'] == asset):
                        current_price = float(price['price'])

                _buy_price = float(WalletList['buy_price'])
                _percentage = (
                    (current_price - _buy_price) / current_price) * 100

                # %3 kâr olmadığı sürece elde tut
                if (_percentage > 3):
                    Notify.notify(asset,
                                  'Satış Alarmı - Pmax',
                                  'Trader V3',
                                  sound=True)
                    print("<b><blue>SATILDI</blue> </b>")
                    print("<b><green>Pmax Sinyali</green>")
                    print("<b>{}</b>".format(asset))

                    # Silinecek
                    WatchList = track.find_one({'asset': asset},
                                               sort=[('_id', DESCENDING)])
                    WalletList = wallet.find_one({'asset': asset},
                                                 sort=[('_id', DESCENDING)])

                    # print('WalletList', WalletList)
                    # print('Watchlist', WatchList)

                    Notify.notify(asset, 'SATIŞ', 'Trader V3', sound=True)
                    # Silinecek

                    sold.insert_one({
                        'asset':
                        asset,
                        'pmax':
                        result['pmX_4_0.1_4_7'][len(result) - 1],
                        'sold_price':
                        result['close'][len(result) - 1],
                        'buy_data':
                        WalletList,
                        'sold_time':
                        datetime.now(),
                        'candle_data':
                        numpy_data,
                        'reason':
                        'Pmax',
                    })
                    wallet.delete_one({'asset': asset})
        else:
            #  UP ise
            if (WatchList == None):  # Takip listesinde değilse
                if (WalletList == None):  # Cüzdanda değilse
                    # Notify.notify(asset, 'WatchList Aktif', 'Trader V3', sound=True)

                    print("<b><green>Takip Listesine Alındı</green> </b>")
                    print("<b>{}</b>".format(asset))
                    print("<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>".
                          format(result))

                    track.insert_one({
                        'asset':
                        asset,
                        'pmax':
                        result['pmX_4_0.1_4_7'][len(result) - 1],
                        'buy_price':
                        result['close'][len(result) - 1],
                        'buy_time':
                        datetime.now(),
                        'candle_data':
                        numpy_data,
                    })
            else:  # Takip listesindeyse
                if (WalletList == None):  # Cüzdanda değilse
                    time.sleep(1)
                    try:
                        candles = client.get_all_tickers()
                    except:
                        time.sleep(30)
                        candles = client.get_all_tickers()
                        pass

                    for candle in candles:
                        if (candle['symbol'] == asset):
                            current_price = float(candle['price'])
                    buy_price = WatchList['buy_price']
                    percentage = (
                        (current_price - buy_price) / current_price) * 100
                    if (percentage >= 3):
                        # Notify.notify(asset, 'Alım Sinyali %3', 'Trader V3', sound=True)
                        print("<b><blue>SATIN ALINDI</blue> </b>")
                        print("<b>{}</b>".format(asset))
                        print(
                            "<b><fg 0,95,0><white>{}</white></fg 0,95,0></b>".
                            format(result))
                        wallet.insert_one({
                            'asset': asset,
                            'buy_price': current_price,
                            'buy_time': datetime.now(),
                            'track_data': WatchList,
                            'candle_data': numpy_data,
                        })
                        track.delete_one({'asset': asset})