Example #1
0
def colorful_print(raw):

    # print colorful text in terminal.

    lines = raw.split('\n')
    colorful = True
    detail = False
    for line in lines:
        if line:
            if colorful:
                colorful = False
                print(white(line, bg='green') + '\n')
                #                print(colored(line, 'white', 'on_green')+'\n')
                continue
            elif line.startswith('例'):
                print(line + '\n')
                continue
            elif line.startswith('【'):
                print(white(line, bg='green') + '\n')
                #                print(colored(line, 'white', 'on_green')+'\n')
                detail = True
                continue

            if not detail:
                print(yellow(line + '\n'))
#                print(colored(line+'\n', 'yellow'))
            else:
                print(blink(line) + '\n')
Example #2
0
    def verify(self, handle):
        """
        Verifies that the user has valid credentials for accessing Tweepy API
        :param handle: the handle of the twitter user that the bot operator wishes to mimic
        :return: a 4-tuple of an API object, the bot's handle, the standardized handle of the other user, and the
            actual handle of the other user (can have uppercase letters)
        """
        sys.stdout.write(colors.yellow("verifying credentials"))
        thread = Thread(target=self.loading())  # lol
        thread.daemon = True  # kill this thread if program exits
        thread.start()

        api = self.authorize()
        handle = handle.strip().lower()  # standardize name formatting for folder name
        try:
            who_am_i = handle if handle in "test" else api.get_user(handle).screen_name  # test that API works
            me = api.me().screen_name
        except TweepError as e:
            err = e[:][0][0]["message"]
            raise ValueError("Awh dang dude, you gave me something bad: %s" % err)

        thread.join()  # lol
        print colors.white(" verified\n") + colors.cyan("starting up bot ") + colors.white("@" + me) + colors.cyan(
            " as ") + colors.white("@" + who_am_i) + colors.cyan("!\n")
        return api, me, handle, who_am_i  # api, the bot's name, the other user's name, full version of user's name
Example #3
0
def spammerv2():
    time.sleep(2)
    print(red())
    print("""

    █▀ █▀█ ▄▀█ █▀▄▀█ █▀▄▀█ █▀▀ █▀█   █░█ ▀█
    ▄█ █▀▀ █▀█ █░▀░█ █░▀░█ ██▄ █▀▄   ▀▄▀ █▄
    \n\nby Alfo

    """)

    print("[+] The spam is starting...", white())
    print("[?] If you want to change the word write them in spammer.txt",
          white())
    print("Good Trolling, by alfo", green())

    try:
        f = open("spammer.txt", 'r')
    except IOError:
        print("[-] No file named spammer.txt creating new", red())
        f = open("spammer.txt", "x")

    for word in f:
        keyboard.write(word, 0.01)
        keyboard.press('enter')
        time.sleep(0.5)
        print("[+] Succesfully Writed" + " " + word, green())
Example #4
0
 def get_received_headers(self):
     received = self.eml.get_all("Received")
     if received:
         for receive in received:
             print(bold(white(f"<Received>")), ":", receive)
     else:
         print("No", bkgrd(white("`Received`"), 'red'),
               "header for this email")
Example #5
0
 def run(self):
     green('Starting watch for {0}'.format(market))
     yellow(
         'Checked every 0.5 seconds, only price/percentage changes will be shown'
     )
     yellow(
         'Price/Percentage changes are based on the moment the watch is started'
     )
     yellow(
         'Please note the Timestamp is taken from Bittrex, can be different then yours'
     )
     red('q+enter to return to Main Menu')
     lastprice = '0'
     try:
         values = r.hmget(market, 'Ask')
         start_price = float(values[0])
     except:
         white(
             'Currency not available... or unable to retrieve data from redis.pontstrader.com'
         )
     else:
         while not self._stopevent.isSet():
             try:
                 values = r.hmget(market, 'Ask', 'TimeStamp')
                 price = float(values[0])
                 timestamp = values[1]
             except:
                 red('Unable to retrieve data from redis.pontstrader.com, trying to recover...'
                     )
             else:
                 percent = 100 * (float(price) - float(start_price)
                                  ) / float(start_price)
                 if price != lastprice:
                     if percent < 0.00:
                         white(
                             '{0} - The {1} price for 1 {2} is {3:.8f} {4}'
                             .format(timestamp, trade, currency, price,
                                     trade) +
                             (Fore.RED + ' ({0:.2f})%'.format(percent)))
                         lastprice = price
                     elif percent > 0.00:
                         white(
                             '{0} - The {1} price for 1 {2} is {3:.8f} {4}'
                             .format(timestamp, trade, currency, price,
                                     trade) +
                             (Fore.GREEN +
                              ' ({0:.2f})%'.format(percent)))
                         lastprice = price
                     else:
                         white(
                             '{0} - The {1} price for 1 {2} is {3:.8f} {4} ({5:.2f}%)'
                             .format(timestamp, trade, currency, price,
                                     trade, percent))
                         lastprice = price
                 time.sleep(0.5)
             self._stopevent.wait(self._sleepperiod)
         white('Returning to Main Menu')
Example #6
0
 def clear_tweets(self):
     """
     DANGER: removes all tweets from current bot account
     """
     for status in tweepy.Cursor(self.api.user_timeline).items():
         try:
             self.api.destroy_status(status.id)
             print colors.white("deleted successfully")
         except tweepy.TweepError:
             print colors.red("Failed to delete:"), status.id
async def masspurge(ctx):
    global deleted

    await ctx.message.delete()
    async for message in ctx.message.channel.history(limit=500).filter(
            lambda m: m.author == client.user).map(lambda m: m):
        await message.delete()
        deleted += 1
        system('title [Discord Message Deleter] - Deleted Messages: %s' %
               deleted)
        print('%s[%s%s%s] Deleted Message%s: %s%s' %
              (red(), white(), strftime('%H:%M:%S', gmtime()), red(), white(),
               message.content, reset()))
Example #8
0
 def printBiomeMap(self):
     for y in range(0, self.height):
         print("")
         for x in range(0, self.width):
             if (self.tiles[x][y].settlement != None):
                 sys.stdout.write(
                     color(self.tiles[x][y].settlement.type,
                           self.tiles[x][y].colorX))
             elif (self.tiles[x][y].color == "cyan"):
                 sys.stdout.write(cyan(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "white"):
                 sys.stdout.write(white(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "green"):
                 sys.stdout.write(green(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "yellow"):
                 sys.stdout.write(yellow(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "blue"):
                 sys.stdout.write(blue(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "magenta"):
                 sys.stdout.write(magenta(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "red"):
                 sys.stdout.write(red(self.tiles[x][y].biome))
             elif (self.tiles[x][y].colorX != None):
                 sys.stdout.write(
                     color(self.tiles[x][y].biome, self.tiles[x][y].colorX))
             else:
                 sys.stdout.write(self.tiles[x][y].biome)
Example #9
0
def main():
    print(
        colors.blue(
            ' ________________________\n|SK-WifiDeath ' + ver +
            '       |\n| Written By Skittles_  |\n|       ssssssss        |\n|    sss        sss     |\n| ss     sssss      ss  |\n|    ssss     ssss      |\n|         sss           |\n|          _            |\n|_________|S|___________|'
        ))
    print('')
    print('')
    selectionFromMenu = input(
        colors.white(
            'What would you like to do?\n'
            '1)Deauth a client\n2)Deauth an Access Point\nE)Exit WifiDeath\nSKWD>'
        ))

    if selectionFromMenu == '1':
        system('clear')
        print('OK, Client Deauth.')
        deauth.wifiDeauthClient()
        mainMenu()

    elif selectionFromMenu == '2':
        print('OK, AP Deauth.')
        deauth.wifiDeauthAP()
        mainMenu()
    elif selectionFromMenu == 'E':
        sys.exit()
    else:
        if name == 'nt':
            system('cls')
        else:
            system('clear')
        mainMenu()
Example #10
0
def import_missing(module):
  exctype, exc = sys.exc_info()[:2]

  print red('Error:', bold=True), 'Missing module', module
  print str(exc)
  print 'To fix the issue please run:'
  print '$', white('sudo pip install %s' % module, bold=True)
  sys.exit(1)
Example #11
0
    def get_optional_header(self):
        headers = [
            bold(blue("Fields")),
            bold(red("FileOffset")),
            bold(green("Offset")),
            bold(orange("Value"))
        ]
        table = []

        print("\n\t\t\t\t", bold(white("OPTIONAL HEADER")), "\n")
Example #12
0
 def chain(self, max_length=TWEET_MAX_LENGTH):
     """
     Generates and prints a sentence using Markov chains. User can specify the maximum length of the tweet lest it
     defaults to the maximum tweet length
     :param max_length: the maximum number of characters allowed in the tweet - by default, max tweet length
     :return: the markov chain text that was generated
     """
     if max_length < MIN_TWEET_LENGTH:
         raise ValueError(colors.red("Tweets must be larger than %s chars" % MIN_TWEET_LENGTH))
     chain_text = self.chain_maker.generate_chain(max_length)
     return colors.white("@" + self.fancy_handle) + colors.yellow(" says: ") + chain_text
	def parse_reputation(self, rep):
		rep = loads(rep)
		premium_keys = ("success", "message", "request_id",
						"connection_type", "abuse_velocity")

		print(bkgrd(white("[Reputation]"), "blue"))
		for key, value in rep.items():
			if key in premium_keys:
				continue
			print("\t\u25aa " + key.capitalize().replace("_", " "), "::", value)
		print("\n\tCheck out this link for more info about results:" \
			  "\n\t\t- https://www.ipqualityscore.com/documentation/proxy-detection/overview\n")
Example #14
0
 def run(self, func, args=None):
     if self._file:
         with open(self._file, "rb") as f:
             self.eml = message_from_bytes(f.read())
             print(bkgrd(white(" File "), "grey_42"), ":", self._file, "\n")
             if func == self.match_headers:
                 func(args)
             else:
                 func()
     else:
         for entry in scandir(path=self.directory):
             file_name = entry.name
             if entry.is_file():
                 with open(f"{self.directory}{sep}{entry.name}", "rb") as f:
                     self.eml = message_from_bytes(f.read())
                     print(bkgrd(white(" File "), "grey_42"), ":",
                           file_name, "\n")
                     if func == self.match_headers:
                         func(args)
                     else:
                         func()
                     print()
	def parse_reputation(self, rep):
		rep = loads(rep)
		premium_keys = ("message", "success", "request_id")
		age = ("domain_age", "first_seen")

		print(bkgrd(white("[Reputation]"), "orange_red_1"))
		for key, value in rep.items():
			if key in premium_keys:
				continue
			elif key in age:
				print("\t\u2022 " + key.capitalize().replace("_", " "), "::")
				for k, v in rep[key].items():
					print(f"\t\t{k.capitalize()} -> {v}")
			else:
				print("\t\u2022 " + key.capitalize().replace("_", " "), "::", value)
		print("\n\tCheck out this link for more info about results:" \
			  "\n\t\t- https://www.ipqualityscore.com/documentation/email-validation/overview\n")
Example #16
0
    def parse_subset(self, logs, file):
        """

        :param logs:
        :param file:
        :return:
        """
        regex = re.compile(r"(?:(" + re.escape(white(file)) + ")|(" +
                           re.escape(magenta(file)) +
                           "))"  # Starts with the file name
                           r"\s+\|\s+([0-9;]+)\s+\|\s+"  # Nodes Count
                           r"([a-zA-Z0-9 \n\|\:\;]+)\+---"  # Colonnes
                           )
        regex_tests = re.compile(r"(?:(?:\|\s+)+)?((?:[A-Za-z0-9:]+\s)+)")
        for _, match, nodes, text in regex.findall(logs):
            tests = [l.strip() for l in regex_tests.findall(text)]
            return nodes, tests
Example #17
0
    def get_file_header(self):
        headers = [
            bold(blue("Fields")),
            bold(red("FileOffset")),
            bold(green("Offset")),
            bold(orange("Value"))
        ]
        table = []

        print("\n\t\t\t\t", bold(white("FILE HEADER")), "\n")
        for field, value in self.pedump["FILE_HEADER"].items():
            if isinstance(value, dict):
                t = [field]
                for subvalue in value.values():
                    if isinstance(subvalue, int):
                        subvalue = hex(subvalue)
                    t.append(subvalue)
                table.append(t)
        print(tabulate(table, headers=headers))
Example #18
0
def cmd_study(s, r):
    '''study <object>|<object type>

    Learn more information about an object, or one of
        the different types of clonable objects that
        are available.

    See the lists of cloneables using the @list command.

    '''

    objname = r.get('objname', '')
    objtzid = r.get('objtzid', 0)
    if not objname and not objtzid:
        s.message('Try: @study <object>')
        raise SyntaxError

    obj = find(r, s.room, s.player, s.room)
    if obj is not None:
        doc = obj.__doc__
        name = class_as_string(obj)
        found = obj
    else:
        found = False
        for mod in items, mobs, rooms:
            for name in mod.classes():
                if objname == name:
                    found = name
                    cls = getattr(mod, name)
                    doc = cls.__doc__

        if not found:
            s.message('No such thing to study.')
            return

    if doc is None:
        doc = '... but it is still a mystery'

    name = colors.white(name)
    s.message('You study the', found)
    msgs = doc.split('\n')
    s.mlmessage(msgs, indent=4)
Example #19
0
def menu(apikey, apisecret, pushover_user, pushover_app, pushbullet_token,
         redis_password):

    import sys
    import time
    import threading
    import os
    from buy import buy
    from sell import sell
    from buysell import buysell
    from balances import balances
    from orderbook import orderbook
    from watch import watch
    from withdraw import withdraw
    from deposit import deposit
    from arbitrage import arbitrage
    from trailing import trailing
    from takeprofit import takeprofit
    from stoplosstakeprofit import stoplosstakeprofit
    from trailingtakeprofit import trailingtakeprofit
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init
    init()

    while True:
        white((30 * '-'))
        green('P O N T S T R A D E R . C O M')
        white((30 * '-'))
        yellow('1. Buy')
        yellow('2. Sell')
        yellow('3. Buy and Sell')
        yellow('4. Balances')
        yellow('5. Orderbook')
        yellow('6. Watch coin')
        yellow('7. Withdraw')
        yellow('8. Deposit')
        yellow('9. Arbitrage')
        yellow('10. Trailing Stop Loss (24/7)')
        yellow('11. Take Profit (BETA + 24/7)')
        yellow('12. Stop Loss + Take Profit (BETA + 24/7)')
        yellow('13. Trailing + Take Profit (BETA + 24/7)')
        red('14. Exit')
        white((30 * '-'))

        try:
            choice = raw_input(Fore.WHITE + 'Enter your choice [1-14] : ')
            choice = int(choice)
        except:
            red('Invalid number. Try again...')

        # BUY
        if choice == 1:
            buy(apikey, apisecret, redis_password)

        # SELL
        elif choice == 2:
            sell(apikey, apisecret, redis_password)

        # BUY AND SELL
        elif choice == 3:
            buysell(apikey, apisecret, redis_password)

        # SHOW WALLETS
        elif choice == 4:
            balances(apikey, apisecret, redis_password)

        # OPEN ORDERS
        elif choice == 5:
            orderbook(apikey, apisecret, redis_password)

        # WATCH
        elif choice == 6:
            watch(apikey, apisecret, redis_password)

        # WITHDRAW
        elif choice == 7:
            withdraw(apikey, apisecret)

        # DEPOSIT
        elif choice == 8:
            deposit(apikey, apisecret)

        # ARBITRAGE
        elif choice == 9:
            arbitrage(redis_password)

        # TRAILING
        elif choice == 10:
            trailing(apikey, apisecret, pushover_user, pushover_app,
                     pushbullet_token, redis_password)

        # TAKE PROFIT
        elif choice == 11:
            takeprofit(apikey, apisecret, pushover_user, pushover_app,
                       pushbullet_token, redis_password)

        # STOP LOSS TAKE PROFIT
        elif choice == 12:
            stoplosstakeprofit(apikey, apisecret, pushover_user, pushover_app,
                               pushbullet_token, redis_password)

        # TRAILING TAKE PROFIT
        elif choice == 13:
            trailingtakeprofit(apikey, apisecret, pushover_user, pushover_app,
                               pushbullet_token, redis_password)

        # EXIT
        elif choice == 14:
            count = threading.activeCount()
            if count > 1:
                threads = threading.enumerate()
                thread_counter = 0
                for t in threading.enumerate():
                    if 'arbitrage' in t.name:
                        pass
                    elif 'Main' in t.name:
                        pass
                    else:
                        thread_counter += 1
                if thread_counter > 0:
                    yellow(
                        'WARNING: There are currently {0} active trade(s), are you sure you want to exit?'
                        .format(thread_counter))
                    green('1. yes')
                    red('2. no')
                    try:
                        yes_no = raw_input(Fore.WHITE +
                                           'Enter your choice [1-2] : ')
                        yes_no = int(yes_no)
                    except:
                        white('Invalid number... going back to Main Menu')
                    if yes_no == 1:
                        white('Exiting...')
                        sys.exit()
                    elif yes_no == 2:
                        white('Good... going back to Main Menu')
                    else:
                        white('Invalid number... going back to Main Menu')
                else:
                    white('Exiting...')
                    sys.exit()
            else:
                white('Exiting...')
                sys.exit()

        # ELSE EXIT
        else:
            white('Invalid number. Try again...')
Example #20
0
def balances(key, secret, redis_password):

    import time, json, sys, os, redis
    from pprint import pprint
    from time import gmtime, strftime
    from bittrex import bittrex
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init
    init()

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    while True:
        try:
            api = bittrex(key, secret)
        except:
            white('Bittrex API error: {0}'.format(api))

        white((30 * '-'))
        green('   B A L A N C E S')
        white((30 * '-'))
        try:
            get_balances = api.getbalances()
            green('Currency\tBalance\t\t\tAvailable\t\tPending\t\tBTC Value')
            total_btc = 0
            usdt = 0
            for coin in get_balances:
                balance = coin["Balance"]
                if (balance != 0.0 and not None):
                    available = coin["Available"]
                    currency = coin["Currency"]
                    pending = coin["Pending"]
                    if currency == 'BTC':
                        white('{0}\t\t{1:.8f}\t\t{2:.8f}\t\t{3:.8f}\t{4:.8f}'.
                              format(currency, balance, available, pending,
                                     balance))
                        last = balance
                        total_btc += last
                    elif currency == 'USDT':
                        white('{0}\t\t{1:.8f}\t\t{2:.8f}\t\t{3:.8f}'.format(
                            currency, balance, available, pending))
                        usdt = float(balance)
                        last = '0'
                    else:
                        try:
                            market = 'BTC-{0}'.format(currency)
                            summary = api.getmarketsummary(market)
                            values = r.hmget(market, 'Ask')
                            last = float(values[0]) * float(balance)
                            total_btc += last
                            white(
                                '{0}\t\t{1:.8f}\t\t{2:.8f}\t\t{3:.8f}\t{4:.8f}'
                                .format(currency, balance, available, pending,
                                        last))
                        except:
                            white(
                                '{0}\t\t{1:.8f}\t\t{2:.8f}\t\t{3:.8f}'.format(
                                    currency, balance, available, pending))
            market = 'USDT-BTC'
            summary = api.getmarketsummary(market)
            total_usd = float(
                summary[0]['Last']) * float(total_btc) + float(usdt)
            yellow('Estimated Value: {0:.8f} BTC / {1:.8f} USD'.format(
                total_btc, total_usd))
            output = (Fore.YELLOW +
                      'Refresh: r+enter | Return to Main Menu: q+enter : ')
            refresh = raw_input(output)
            refresh = str(refresh)
            if refresh == 'r':
                green('Ok, refreshing in 5 seconds... (to prevent spam)')
                time.sleep(5)
            elif refresh == 'q':
                break
            else:
                white(
                    'Invalid input, refreshing in 5 seconds... (to prevent spam)'
                )
                time.sleep(5)
        except:
            white('Bittrex API error')
            white('Going back to Main Menu')
            time.sleep(2)
            break
def stoplosstakeprofit(key, secret, pushover_user, pushover_app,
                       pushbullet_token, redis_password):

    import sys, os, json, time, threading, requests, redis
    from datetime import datetime
    from bittrex import bittrex
    from pushover import send_pushover
    from pushbullet import send_pushbullet
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init
    init()

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    global sltp_messages
    global sltp_messages_done

    try:
        sltp_messages
    except NameError:
        sltp_messages = {}
    else:
        pass

    try:
        sltp_messages_done
    except NameError:
        sltp_messages_done = {}
    else:
        pass

    white((45 * '-'))
    green('   S T O P  L O S S  T A K E  P R O F I T')
    white((45 * '-'))
    while True:
        status_update = False
        gobuy = False
        try:
            threads = threading.enumerate()
            thread_counter = 0
            for t in threading.enumerate():
                if t.name.startswith('sltp-'):
                    thread_counter += 1
            if thread_counter > 0:
                yellow('There are currently {0} active sltp trade(s):'.format(
                    thread_counter))
            else:
                yellow('There are currently no active sltp trades')
            white(
                'Would you like to make another sltp trade, check active trades or check history of your sltp trades?'
            )
            green('1. New trade')
            yellow('2. Active trades')
            yellow('3. History')
            red('4. Back to Main Menu')
            try:
                yes_no = raw_input(Fore.WHITE + 'Enter your choice [1-4] : ')
                yes_no = int(yes_no)
                white((40 * '-'))
            except:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
            if yes_no == 1:
                pass
            elif yes_no == 2:
                while True:
                    try:
                        trades = 0
                        for k, v in sltp_messages.iteritems():
                            trades += 1
                            if v.startswith('sltp-'):
                                print v
                        if trades == 0:
                            red('There is currently no sltp trade status available!'
                                )
                            white((40 * '-'))
                        white('Refresh, new trade or back to Main Menu?')
                        green('1. Refresh')
                        yellow('2. New Trade')
                        red('3. Back')
                        go_break = False
                        try:
                            yes_no = raw_input(Fore.WHITE +
                                               'Enter your choice [1-3] : ')
                            yes_no = int(yes_no)
                            white((40 * '-'))
                        except:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                        if yes_no == 1:
                            pass
                        elif yes_no == 2:
                            break
                        elif yes_no == 3:
                            white('\nOk... going back to Main Menu')
                            time.sleep(1)
                            break
                        else:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                    except:
                        red('\nUnable to retrieve active threads data... going back to Main Menu'
                            )
                        break
                if yes_no == 3 or go_break == True:
                    break
            elif yes_no == 3:
                while True:
                    try:
                        trades = 0
                        for k, v in sltp_messages_done.iteritems():
                            trades += 1
                            if v.startswith('sltp-'):
                                print v
                        if trades == 0:
                            red('There is currently no sltp trade history available!'
                                )
                            white((40 * '-'))
                        white('Refresh, new trade or back to Main Menu?')
                        green('1. Refresh')
                        yellow('2. New Trade')
                        red('3. Back')
                        go_break = False
                        try:
                            yes_no = raw_input(Fore.WHITE +
                                               'Enter your choice [1-3] : ')
                            yes_no = int(yes_no)
                            white((40 * '-'))
                        except:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                        if yes_no == 1:
                            pass
                        elif yes_no == 2:
                            break
                        elif yes_no == 3:
                            white('\nOk... going back to Main Menu')
                            time.sleep(1)
                            break
                        else:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                    except:
                        red('\nUnable to retrieve active threads data... going back to Main Menu'
                            )
                        break
                if yes_no == 3 or go_break == True:
                    break
            elif yes_no == 4:
                white('\nOk... going back to Main Menu')
                time.sleep(1)
                break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
        except:
            red('\nUnable to retrieve active threads... there is something wrong please contact p0nts!'
                )
            break

        try:
            market = raw_input(
                Fore.WHITE + 'Market? (e.g. BTC-NEO / ETH-LTC / USDT-OMG) : ')
            market = str(market.upper())
            trade = market.split('-')[0]
            currency = market.split('-')[1]
            check_status = r.exists(market)
            if check_status != True:
                white('Unsupported market... going back to Main Menu')
                time.sleep(1)
                break
        except:
            white('\nInvalid input... going back to Main Menu')
            time.sleep(1)
            break

        if market.startswith('BTC'):
            trade = 'BTC'
        elif market.startswith('ETH'):
            trade = 'ETH'
        elif market.startswith('USDT'):
            trade = 'USDT'
        else:
            white('Unsupported market... going back to Main Menu')
            time.sleep(1)
            break

        try:
            api = bittrex(key, secret)
            available = api.getbalance(trade)
            yellow('You have {0:.8f} {1} available in total'.format(
                available['Available'], trade))
        except:
            print 'Unable to retrieve available {0} balance from Bittrex... try again later'.format(
                trade)
            time.sleep(1)
            break

        try:
            value = raw_input(Fore.WHITE +
                              'How much {0}? (excl. fee) : '.format(trade))
            value = float(value)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        else:
            try:
                available = api.getbalance(trade)
            except:
                red('Unable to retrieve balance information from Bittrex... going back to Main Menu'
                    )
                time.sleep(1)
                break
            else:
                if float(value) > float(available['Available']):
                    red('You have less {0} balance available than you want to trade with... going back to Main Menu'
                        .format(trade))
                    time.sleep(1)
                    break

        oneortwotargets = False
        if value < 0.00100000:
            red('The minimum trade size on Bittrex is 100k sat')
            time.sleep(1)
            break
#    elif value >= 0.00200000:
#      green('You are trading more than or equal to 200k satoshi, which means you are eligible to use multiple sell targets due to Bittrex new policy of 100k satoshi minimum per trade.')
#      green(' - One sell target = sell 100% at .. satoshi')
#      green(' - Two sell targets = sell 50% at .. satoshi, and the other 50% at x satoshi')
#      white((40 * '-'))
#      yellow('Would you like to use 2 sell targets or just one?')
#      green('1. yes, two')
#      yellow('2. no, just one')
#      red('3. Return to Main Menu')
#      try:
#        oneortwo = raw_input(Fore.WHITE+'Enter your choice [1-3] : ')
#        oneortwo = int(oneortwo)
#      except:
#        white('\nCancelled... going back to Main Menu')
#        time.sleep(1)
#        break
#      if oneortwo == 1:
#        oneortwotargets = True
#      elif oneortwo == 2:
#        pass
#      elif oneortwo == 3:
#        white('Ok... going back to Main Menu')
#        time.sleep(1)
#        break
#      else:
#        white('\nInvalid number... going back to Main Menu')
#        time.sleep(1)
#        break
        else:
            yellow(
                'You are trading with less than 200k satoshi, which means you are not eligible to use multiple sell targets due to Bittrex new policy of 100k satoshi per trade minimum, so we will stick with one.'
            )

        try:
            values = r.hmget(market, 'Ask', 'MarketName', 'BaseVolume',
                             'Volume', 'OpenBuyOrders', 'OpenSellOrders',
                             'High', 'Low', 'Last', 'Bid')
        except:
            white(
                'API error: Unable to retrieve pricing information for redis.pontstrader.com... going back to Main Menu'
            )
            time.sleep(1)
            break

        white((40 * '-'))
        green('   M A R K E T  I N F O R M A T I O N')
        white((40 * '-'))
        yellow('- Market:           {0}'.format(market))
        yellow('- Volume:           {0:.8f}'.format(float(values[2])))
        yellow('- 24H volume:       {0:.8f}'.format(float(values[3])))
        yellow('- Open buy orders:  {0}'.format(values[4]))
        yellow('- Open sell orders: {0}'.format(values[5]))
        yellow('- 24H high:         {0:.8f}'.format(float(values[6])))
        yellow('- 24H low:          {0:.8f}'.format(float(values[7])))
        yellow('- Last:             {0:.8f}'.format(float(values[8])))
        yellow('- Ask:              {0:.8f}'.format(float(values[0])))
        yellow('- Bid:              {0:.8f}'.format(float(values[9])))
        white((40 * '-'))

        try:
            white('Configure Stop Loss and Target in satoshi or percentage?')
            green('1. Satoshi')
            yellow('2. Percentage')
            satorper = raw_input(Fore.WHITE + 'Enter your choice [1-2] : ')
            satorper = int(satorper)
            white((40 * '-'))
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        else:
            if satorper == 1:
                try:
                    stoploss = raw_input(Fore.WHITE +
                                         'Stop Loss? [eg. 0.00436] : ')
                    stoploss = float(stoploss)
                except:
                    white('\nInvalid number... going back to Main Menu')
                    time.sleep(1)
                    break
            elif satorper == 2:
                try:
                    stoploss = raw_input(
                        Fore.WHITE +
                        'Stop Loss percentage (without %)? [eg. 5] : ')
                    stoploss = float(stoploss)
                except:
                    white('\nInvalid number... going back to Main Menu')
                    time.sleep(1)
                    break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break

        if oneortwotargets == True:
            pass


#      try:
#        target1 = raw_input(Fore.WHITE+'Target 1? 50% of the trade value will be sold here [eg. 0.00436] : ')
#        target1 = float(target1)
#      except:
#        white('\nInvalid number... going back to Main Menu')
#        time.sleep(1)
#        break
#
#      try:
#        target2 = raw_input(Fore.WHITE+'Target 2? 50% of the trade value will be sold here [eg. 0.00436] : ')
#        target2 = float(target2)
#      except:
#        white('\nInvalid number... going back to Main Menu')
#        time.sleep(1)
#        break
#      white((40 * '-'))
#      green('   B U Y  I N F O R M A T I O N')
#      yellow('- Buyprice:               {0:.8f}'.format(float(values[0])))
#      yellow('- Target 1:               {0:.8f}'.format(float(target1)))
#      yellow('- Target 2:               {0:.8f}'.format(float(target2)))
#      yellow('- Stop Loss:              {0:.8f}'.format(float(stoploss)))
#      yellow('Because the price could have changed during your input...')
#      yellow('Pontstrader wil calculate new targets and stop loss based on the buyprice.')
        else:
            if satorper == 1:
                try:
                    target = raw_input(
                        Fore.WHITE +
                        'Target? 100% of the trade value will be sold here [eg. 0.00436] : '
                    )
                    target = float(target)
                except:
                    white('\nInvalid number... going back to Main Menu')
                    time.sleep(1)
                    break
            elif satorper == 2:
                try:
                    target = raw_input(
                        Fore.WHITE +
                        'Target in percentage (without %)?  [eg. 5] : ')
                    target = float(target)
                except:
                    white('\nInvalid number... going back to Main Menu')
                    time.sleep(1)
                    break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
            white((40 * '-'))
            green('   B U Y  I N F O R M A T I O N')
            yellow('- Buyprice:               {0:.8f}'.format(float(
                values[0])))
            if satorper == 1:
                yellow('- Stop Loss:              {0:.8f}'.format(
                    float(stoploss)))
                yellow('- Target:                 {0:.8f}'.format(
                    float(target)))
            elif satorper == 2:
                stop_per = float(stoploss)
                tar_per = float(target)
                stoploss_percentage = float(values[0]) / 100 * float(stoploss)
                target_percentage = float(values[0]) / 100 * float(target)
                stoploss = float(values[0]) - float(stoploss_percentage)
                target = float(values[0]) + float(target_percentage)
                yellow('- Stop Loss:              {0:.8f} ({1:.2f}%)'.format(
                    float(stoploss), float(stop_per)))
                yellow('- Target:                 {0:.8f} ({1:.2f}%)'.format(
                    float(target), float(tar_per)))
            white((40 * '-'))
            yellow(
                'Because the price could have changed during your input, the buyprice may differ a little from the above prices!'
            )

        white((40 * '-'))
        white('Proceed?')
        green('1. yes')
        red('2. no, return to Main Menu')
        try:
            proceed = raw_input(Fore.WHITE + 'Enter your choice [1-2] : ')
            proceed = int(proceed)
        except:
            white('\nCancelled... going back to Main Menu')
            time.sleep(1)
            break
        if proceed == 1:
            try:
                values = r.hmget(market, 'Ask')
                ask = float(values[0])
                amount = float(value) / float(ask)
                orderbook = api.getorderbook(market, type='sell')
                orderbook_rate = orderbook[0]['Rate']
                orderbook_quantity = orderbook[0]['Quantity']
                if float(amount) < float(orderbook_quantity):
                    gobuy = True
                    break
                else:
                    while float(amount) > float(orderbook_quantity):
                        time.sleep(1)
                        orderbook = api.getorderbook(market, type='sell')
                        orderbook_rate = orderbook[0]['Rate']
                        orderbook_quantity = orderbook[0]['Quantity']
                        values = r.hmget(market, 'Ask')
                        ask = float(values[0])
                        amount = float(value) / float(ask)
                        yellow(
                            'Waiting for the volume to rise on lowest Ask to buy all for the same price.'
                        )
                    gobuy = True
                    break
            except:
                white(
                    'API error: Unable to create a buyorder... going back to Main Menu'
                )
                time.sleep(1)
                break
        elif proceed == 2:
            white('Ok... going back to Main Menu')
            time.sleep(1)
            break
        else:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break

    if gobuy == True:

        def start_thread_single(market, currency, amount, ask, stoploss,
                                target):
            time.sleep(1)
            global sltp_messages
            thread_name = threading.current_thread().name
            done = False
            while True:
                values = r.hmget(market, 'Ask')
                ask = float(values[0])
                try:
                    buy = api.buylimit(market, amount, ask)
                except:
                    message = 'Bittrex API error, unable to buy: {0}'.format(
                        buy)
                    sltp_messages[thread_name] = message
                    send_pushover(pushover_user, pushover_app, message)
                    send_pushbullet(pushbullet_token, message)
                    break
                else:
                    time.sleep(0.5)
                    buy_uuid = buy['uuid']
                    time.sleep(0.5)
                    push_send = False
                    try:
                        buyorder = api.getorder(uuid=buy_uuid)
                    except:
                        message = 'Bittrex API error, unable to check the buyorder: {0}'.format(
                            buyorder)
                        sltp_messages[thread_name] = message
                    else:
                        if buyorder['IsOpen'] == True:
                            while buyorder['IsOpen'] == True:
                                message = '{0}: Made a buyorder, waiting until it is filled! Remaining: {1:.8f} {2}'.format(
                                    thread_name, buyorder['QuantityRemaining'],
                                    currency)
                                sltp_messages[thread_name] = message
                                if push_send == False:
                                    try:
                                        send_pushover(pushover_user,
                                                      pushover_app, message)
                                        send_pushbullet(
                                            pushbullet_token, message)
                                        push_send = True
                                    except:
                                        message = 'Unable to send push notification with the buyorder status'
                                        sltp_messages[thread_name] = message
                                try:
                                    buyorder = api.getorder(uuid=buy_uuid)
                                except:
                                    message = 'Bittrex API error, unable to check the buyorder: {0}'.format(
                                        buyorder)
                                    sltp_messages[thread_name] = message
                                    pass
                                time.sleep(10)
                        buyprice = float(ask)
                        lastprice = 0
                    while True:
                        try:
                            time.sleep(0.5)
                            values = r.hmget(market, 'Ask')
                            ask = float(values[0])
                        except:
                            message = 'Unable to retrieve data from redis.pontstrader.com, trying to recover...'
                            sltp_messages[thread_name] = message
                        else:
                            profit_percentage = 100 * (
                                float(ask) - float(buyprice)) / float(buyprice)
                            if float(ask) >= float(target):
                                try:
                                    sell = api.selllimit(
                                        market, amount, target)
                                    sell_uuid = sell['uuid']
                                    time.sleep(0.5)
                                    sellorder = api.getorder(uuid=sell_uuid)
                                    if sellorder['IsOpen'] == True:
                                        while sellorder['IsOpen'] == True:
                                            message = '{0}: Sell target triggered, waiting until the sell order is completely filled! Remaining: {1:.8f}'.format(
                                                thread_name,
                                                sellorder['QuantityRemaining'])
                                            sltp_messages[
                                                thread_name] = message
                                            try:
                                                sellorder = api.getorder(
                                                    uuid=sell_uuid)
                                            except:
                                                pass
                                            time.sleep(2)
                                    message = '{0}: {1} SOLD (Target) | Buy price {2:.8f} | Sell price {3:.8f} | Profit {4:.2f}% (excl. fee)'.format(
                                        thread_name, currency, buyprice,
                                        target, profit_percentage)
                                    del sltp_messages[thread_name]
                                    sltp_messages_done[thread_name] = message
                                    send_pushover(pushover_user, pushover_app,
                                                  message)
                                    send_pushbullet(pushbullet_token, message)
                                    done = True
                                    break
                                except:
                                    message = '{0}: API error: Was unable to create the sellorder... it was cancelled due to:\n{1}'.format(
                                        thread_name, sell)
                                    del sltp_messages[thread_name]
                                    sltp_messages_done[thread_name] = message
                                    send_pushover(pushover_user, pushover_app,
                                                  message)
                                    send_pushbullet(pushbullet_token, message)
                                    done = True
                                    break
                            elif float(ask) <= float(stoploss):
                                try:
                                    sell = api.selllimit(
                                        market, amount, stoploss)
                                    sell_uuid = sell['uuid']
                                    time.sleep(0.5)
                                    sellorder = api.getorder(uuid=sell_uuid)
                                    if sellorder['IsOpen'] == True:
                                        while sellorder['IsOpen'] == True:
                                            message = '{0}: Stop Loss triggered, waiting until the sell order is completely filled! Remaining: {1:.8f}'.format(
                                                thread_name,
                                                sellorder['QuantityRemaining'])
                                            sltp_messages[
                                                thread_name] = message
                                            try:
                                                sellorder = api.getorder(
                                                    uuid=sell_uuid)
                                            except:
                                                pass
                                            time.sleep(2)
                                    message = '{0}: {1} SOLD (Stop Loss) | Buy price {2:.8f} | Sell price {3:.8f} | Loss {4:.2f}% (excl. fee)'.format(
                                        thread_name, currency, buyprice,
                                        stoploss, profit_percentage)
                                    del sltp_messages[thread_name]
                                    sltp_messages_done[thread_name] = message
                                    send_pushover(pushover_user, pushover_app,
                                                  message)
                                    send_pushbullet(pushbullet_token, message)
                                    done = True
                                    break
                                except:
                                    message = '{0}: API error: Was unable to create the sellorder... it was cancelled due to:\n{1}'.format(
                                        thread_name, sell)
                                    del sltp_messages[thread_name]
                                    sltp_messages_done[thread_name] = message
                                    send_pushover(pushover_user, pushover_app,
                                                  message)
                                    send_pushbullet(pushbullet_token, message)
                                    done = True
                                    break
                            else:
                                message = '{0}: {1} | Price {3:.8f} | Buy price {2:.8f} | Stop Loss: {6:.8f} | Target: {4:.8f} | Profit {5:.2f}% (excl. fee)'.format(
                                    thread_name, currency, buyprice, ask,
                                    target, profit_percentage, stoploss)
                                sltp_messages[thread_name] = message

                if done == True:
                    break

        try:
            datetime = datetime.now().strftime("%d-%m-%Y.%H:%M:%S")
            threadname = 'sltp-{0}'.format(datetime)
            if oneortwotargets == True:
                thread = threading.Thread(name=threadname,
                                          target=start_thread,
                                          args=(market, currency, amount, ask,
                                                stoploss, target1, target2))
            else:
                thread = threading.Thread(name=threadname,
                                          target=start_thread_single,
                                          args=(market, currency, amount, ask,
                                                stoploss, target))
            thread.daemon = True
            thread.start()
            green(
                'Made a buy order, to check its status go to the Stop Loss Take Profit menu again... going back to Main Menu in 2 seconds'
            )
            time.sleep(2)
        except:
            red('Unable to start thread... there is something wrong please contact p0nts!'
                )
Example #22
0
def test_global():
  'Test output with global/per_machine tasks'
  print white('THIS SHOULD ONLY APPEAR ONCE', bold=True)
  execute(test_parallel)
  execute(test_parallel)
  execute(test_parallel)
Example #23
0
def buy(key, secret, redis_password):

    import time, json, sys, redis
    from pprint import pprint
    from time import gmtime, strftime
    from bittrex import bittrex
    from menu import menu
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    while True:
        try:
            api = bittrex(key, secret)
            currencies = api.getcurrencies()
            markets = api.getmarkets()
        except:
            white('Bittrex API error: {0}'.format(api))
            white('Going back to Main Menu')
            time.sleep(2)
            break

        white((30 * '-'))
        green('   B U Y  O R D E R')
        white((30 * '-'))
        white('Market?')
        yellow('1. BTC')
        yellow('2. ETH')
        yellow('3. USDT')
        red('4. Back to Main Menu')
        try:
            trade = raw_input(Fore.WHITE + 'Enter your choice [1-4] : ')
            trade = int(trade)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        if trade == 1:
            trade = 'BTC'
        elif trade == 2:
            trade = 'ETH'
        elif trade == 3:
            trade = 'USDT'
        elif trade == 4:
            break
        else:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        try:
            currency = raw_input(
                Fore.WHITE + 'Currency? (e.g. LTC / NEO / OMG) : ').upper()
        except:
            white('Invalid currency... going back to Main Menu')
            time.sleep(1)
            break
        try:
            market = '{0}-{1}'.format(trade, currency)
            available = api.getbalance(trade)
        except:
            print available
            white('\nGoing back to Main Menu')
            time.sleep(1)
            break
        try:
            values = r.hmget(market, 'Last', 'Bid', 'Ask')
            last = float(values[0])
            bid = float(values[1])
            ask = float(values[2])
            white((30 * '-'))
            white('- Price (Last): {0:.8f} {1}'.format(last, trade))
            white('- Price (Bid): {0:.8f} {1}'.format(bid, trade))
            white('- Price (Ask): {0:.8f} {1}'.format(ask, trade))
        except:
            white(
                'Unable to retrieve data from redis.pontstrader.com (Unsupported Market?)'
            )
            white('Going back to Main Menu')
            time.sleep(2)
            break
        for f in currencies:
            if f['Currency'] == currency:
                fee = f['TxFee']
                trade_fee = last * fee
                white('- Fee {0:.8f} {1} ({2:.8f} {3})'.format(
                    fee, currency, trade_fee, trade))
        for m in markets:
            if m['MarketCurrency'] == currency and m['BaseCurrency'] == trade:
                minimum = m['MinTradeSize']
                white('- Minimum ({0}): {1:.8f}'.format(currency, minimum))
        white('- Minimum ({0}): 0.00100000'.format(trade))
        enough = trade_fee + 0.00100000 + last
        if available['Available'] < 0.00100000:
            red('You dont have enough {0} ({1:.8f}) to buy anything!'.format(
                trade, available['Available']))
            time.sleep(1)
            break
        else:
            available_after_fee = available['Available'] - trade_fee
            yellow('You have {0:.8f} {1} available in total'.format(
                available['Available'], trade))
            yellow('Which is {0:.8f} {1} exclusive required fee'.format(
                available_after_fee, trade))
            can_buy_last = available_after_fee / last
            can_buy_bid = available_after_fee / bid
            can_buy_ask = available_after_fee / ask
            green('You can buy up to {0:.8f} {1} for \'Last\' price'.format(
                can_buy_last, currency))
            green('You can buy up to {0:.8f} {1} for \'Bid\' price'.format(
                can_buy_bid, currency))
            green('You can buy up to {0:.8f} {1} for \'Ask\' price'.format(
                can_buy_ask, currency))
            white((30 * '-'))
            white('Buyprice?')
            yellow('1. Last ({0:.8f} {1})'.format(last, trade))
            yellow('2. Bid ({0:.8f} {1})'.format(bid, trade))
            yellow('3. Ask ({0:.8f} {1})'.format(ask, trade))
            yellow('4. Custom')
            red('5. Back to Main Menu')
            try:
                buyprice = raw_input(Fore.WHITE + 'Enter your choice [1-5] : ')
                buyprice = int(buyprice)
            except:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
            if buyprice == 1:
                buy_for = last
                white('Selected \'Last\': {0:.8f} {1}'.format(last, trade))
            elif buyprice == 2:
                buy_for = bid
                white('Selected \'Bid\': {0:.8f} {1}'.format(bid, trade))
            elif buyprice == 3:
                buy_for = ask
                white('Selected \'Ask\': {0:.8f} {1}'.format(ask, trade))
            elif buyprice == 4:
                try:
                    buy_for = raw_input(Fore.WHITE +
                                        'Buyprice? e.g. [0.00000001] : ')
                    buy_for = float(buy_for)
                    white('Selected \'Custom\': {0:.8f} {1}'.format(
                        buy_for, trade))
                except:
                    white('Please provide a proper buyprice! (e.g. {0:.8f})'.
                          format(last))
                    white('Invalid number... going back to Main Menu')
                    time.sleep(2)
                    break
            elif buyprice == 5:
                break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
        try:
            amount = raw_input(Fore.WHITE + 'Amount? : ')
            amount = float(amount)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break

        white((30 * '-'))
        white('Buying {0:.8f} for {1:.8f} {2} each, Proceed?'.format(
            amount, buy_for, trade))
        green('1. yes')
        red('2. no (Back to Main Menu)')
        try:
            yes_no = raw_input(Fore.WHITE + 'Enter your choice [1-2] : ')
            yes_no = int(yes_no)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        if yes_no == 1:
            try:
                apicall = api.buylimit(market, amount, buy_for)
                buy_uuid = apicall['uuid']
                time.sleep(0.5)
                buyorder = api.getorder(uuid=buy_uuid)
                total = amount * buy_for
                green(
                    'Added a buy order for {0:.8f} {1} at {2:.8f} {3} each which is {4:.8f} {3} total'
                    .format(amount, currency, buy_for, trade, total))
                white('Checking status in 2 seconds')
                time.sleep(2)
                if buyorder['IsOpen'] == False:
                    white('Great! Order is completely filled')
                else:
                    white(
                        'Order is not filled yet, would you like to wait up to 120 seconds?'
                        .format(amount, buy_for, trade))
                    green('1. yes')
                    red('2. no (Back to Main Menu)')
                    try:
                        yes_no = raw_input(Fore.WHITE +
                                           'Enter your choice [1-2] : ')
                        yes_no = int(yes_no)
                    except:
                        white('\nInvalid number... going back to Main Menu')
                        time.sleep(1)
                        break
                    if yes_no == 1:
                        yellow(
                            'Script will automatically return to Main Menu after 120 seconds'
                        )
                        time_count = 0
                        time_decrease = 120
                        if buyorder['IsOpen'] == True:
                            while buyorder['IsOpen'] == True:
                                if time_count >= 120:
                                    break
                                yellow(
                                    'Waiting until the buy order is completely filled! Remaining: {0:.8f} ({1} seconds remaining)'
                                    .format(buyorder['QuantityRemaining'],
                                            time_decrease))
                                buyorder = api.getorder(uuid=buy_uuid)
                                time.sleep(10)
                                time_decrease -= 10
                                time_count += 10
                            white(
                                'Unfortunatly the order is not completely filled yet'
                            )
                        else:
                            white('Great! Order is completely filled')
                            time.sleep(1)
                    elif yes_no == 2:
                        white('\nOk... going back to Main Menu')
                        time.sleep(1)
                        break
                    else:
                        white('\nInvalid number... going back to Main Menu')
                        time.sleep(1)
                        break
                white('Returning to Main Menu in 2 seconds...')
                time.sleep(2)
                break
            except:
                white('Bittrex API error: {0}'.format(apicall))
                white('Going back to Main Menu')
                time.sleep(2)
                break
        elif yes_no == 2:
            white('\nCancelled... going back to Main Menu')
            time.sleep(1)
            break
        else:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
Example #24
0
def deposit(key, secret):

  import time, json, sys
  from bittrex import bittrex
  from colors import white, red, green, yellow
  from colorama import Fore, Back, Style, init
  init()

  while True:
    try:
      api = bittrex(key, secret)
    except:
      white('Bittrex API error: {0}'.format(api))
      white('Going back to Main Menu')
      time.sleep(1)
      break

    white((30 * '-'))
    green('   D E P O S I T')
    white((30 * '-'))
    try:
      currency = raw_input(Fore.WHITE+'Currency? (e.g. LTC / NEO / OMG) : ').upper()
    except:
      white('Invalid currency... going back to Main Menu')
      time.sleep(1)
      break
    else:
      try:
        apicall = api.getdepositaddress(currency)
        address = apicall['Address']
        red('WARNING! Bittrex API is crap and does not provide proper addresses on coins that require additional settings such as a tag (XRP) or paymentid (NXT)')
        green('{0} deposit address: {1}'.format(currency, address))
        yellow('Returning to Main Menu in 5 seconds...')
        time.sleep(5)
        break
      except:
        white('Unable to retrieve data from Bittrex... returning to Main Menu')
        time.sleep(1)
        break
Example #25
0
"""),
           style='bold'))
#=================================================================

#======================= Coin Sistem =============================
db_rol_name = "rlcs.coins"  #Get file name
get_coins = open(db_rol_name, 'r')  #Open file
read_db = get_coins.read()  #Read the file
coins = int(read_db)  #Declare the coins
#==================================================================

########################### Show Coins ###################################
print(green("=============== Your Balance ==============="))
print("")
print(white("In G-Coins: " + str(coins), style='bold'))
cdollar = int(coins) / 1000
print(white("In Dollars: $" + str(cdollar), style='bold'))
print("")
print(green("============================================"))
###########################################################################

###################################################################################
if int(coins) == 0:
    print("You cant bet, you have no founds"
          )  #If you have 0 coins the script will auto-exit
    exit()
###################################################################################

#============================+++== COLOR CHOOSE  ======================================
Example #26
0
              (red(), white(), strftime('%H:%M:%S', gmtime()), red(), white(),
               message.content, reset()))


if path.exists('Token.json'):
    with open('Token.json', 'r', encoding='UTF-8', errors='replace') as f:
        try:
            config = json.load(f)
            token = config['token']
        except KeyError:
            with open('Token.json', 'w') as f:
                f.write('{\n    "token": "..."\n}')
            print(
                '> %sReplace "..." with your Discord token inside Token.json '
                '— avoid including spaces or quotation marks%s.\n' %
                (red(), white()))
            system('pause >NUL')
            _exit(0)
    print('> Logging in . . .')
else:
    token = input('> Discord token: ')
    print()
    with open('Token.json', 'w') as f:
        f.write('{\n    "token": "%s"\n}' % token)

try:
    client.run(token, bot=False)
except LoginFailure:
    system('cls')
    print('> %sIncorrect Discord token%s.' % (red(), white()))
    system('pause >NUL')
Example #27
0
async def on_connect():
    system('cls')
    print('> %sLogged in as%s: %s%s\n' %
          (green(), white(), client.user, reset()))
Example #28
0
def orderbook(key, secret, redis_password):

    import time, json, sys, redis
    from pprint import pprint
    from time import gmtime, strftime
    from bittrex import bittrex
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init
    init()

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    while True:
        try:
            api = bittrex(key, secret)
        except:
            white('Bittrex API error: {0}'.format(api))

        try:
            openorders = api.getopenorders(market='')
            white((30 * '-'))
            green('   O P E N  O R D E R S')
            white((30 * '-'))
            if openorders:
                number = 0
                list = []
                green(
                    'Nr.\tMarket\t\tType\t\tAsk\t\tTotal\t\tFilled\t\tCurrent Ask'
                )
                for order in openorders:
                    uuid = order['OrderUuid']
                    market = order['Exchange']
                    ordertype = order['OrderType']
                    total = order['Quantity']
                    remaining = order['QuantityRemaining']
                    filled = total - remaining
                    ask = order['Limit']
                    number += 1
                    values = r.hmget(market, 'Ask')
                    currentprice = float(values[0])
                    list.append(uuid)
                    if len(market) == 6 or len(market) == 7:
                        white(
                            '{0}.\t{1}\t\t{2}\t{3:.8f}\t{4:.8f}\t{5:.8f}\t{6:.8f}'
                            .format(number, market, ordertype, ask, total,
                                    filled, currentprice))
                    else:
                        white(
                            '{0}.\t{1}\t{2}\t{3:.8f}\t{4:.8f}\t{5:.8f}\t{6:.8f}'
                            .format(number, market, ordertype, ask, total,
                                    filled, currentprice))
            else:
                red('No open orders found... going back to Main Menu')
                time.sleep(2)
                break
            yellow('To remove an open order, choose the corresponding number.')
            yellow('q+enter to return to Main Menu')
        except:
            print openorders
            white('\nGoing back to Main Menu')
            time.sleep(1)
            break
        try:
            choose_num = raw_input(
                Fore.WHITE + 'Enter your choice [1-{0}] : '.format(number))
            choose_num = str(choose_num)
        except:
            white('Invalid number... going back to Main Menu')
            time.sleep(1)
            break
        try:
            if choose_num == 'q':
                white('Going back to Main Menu in 2 seconds!')
                time.sleep(2)
                break
            elif choose_num.isdigit():
                choose_num = int(choose_num)
                choose_num = choose_num - 1
                cancel = api.cancel(uuid=list[choose_num])
                white('Order successfully removed')
                time.sleep(2)
                openorders = api.getopenorders(market='')
            else:
                white('Going back to Main Menu in 2 seconds!')
                time.sleep(2)
                break
        except:
            white('Invalid input... going back to Main Menu')
            time.sleep(2)
            break
Example #29
0
def sell(key, secret, redis_password):
  
  import time, json, sys, redis
  from pprint import pprint
  from time import gmtime, strftime
  from bittrex import bittrex
  from colors import white, red, green, yellow
  from colorama import Fore, Back, Style, init
  init()

  try:
    r = redis.Redis(host='redis.pontstrader.com', port=6380, db=0, password=redis_password)
  except:
    white('Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...')
    try:
      r = redis.Redis(host='redis2.pontstrader.com', port=6380, db=0, password=redis_password)
    except:
      white('Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!')
  
  while True:
    try:
      api = bittrex(key, secret)
      currencies = api.getcurrencies()
      markets = api.getmarkets()
    except:
      white('Bittrex API error: {0}'.format(api))
      white('Going back to Main Menu')
      time.sleep(1)
      break
  
    white((30 * '-'))
    green('   S E L L  O R D E R')
    white((30 * '-'))
    try:
      balances = api.getbalances()
      green('Currency\tAvailable')
      number = 0
      list = []
      for coin in balances:
        available = coin["Available"]
        currency = coin["Currency"]
        if available != 0.0 and not None:
          number += 1
          list.append(currency)
          if len(currency) < 5:
            white('{0}. {1}\t\t{2:.8f}'.format(number, currency, available))
          else:
            white('{0}. {1}\t{2:.8f}'.format(number, currency, available))
    except:
      white('Bittrex API error: {0}'.format(balances))
      white('Going back to Main Menu')
      time.sleep(2)
      break
    try:
      choose_num = raw_input(Fore.WHITE+'Enter your choice [1-{0}] (q+enter to return to Main Menu) : '.format(number))
      choose_num = int(choose_num)
    except:
      white('Going back to Main Menu')
      time.sleep(1)
      break
    try:
      choose_num = choose_num - 1
      if choose_num == -1:
        white('Invalid number... going back to Main Menu')
        time.sleep(1)
        break
      green('Starting sell for {0}'.format(list[choose_num]))
      white((30 * '-'))
      white('Market?')
      yellow('1. BTC')
      yellow('2. ETH')
      yellow('3. USDT')
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      trade = raw_input(Fore.WHITE+'Enter your choice [1-3] : ')
      trade = int(trade)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if trade == 1:
      trade = 'BTC'
    elif trade == 2:
      trade = 'ETH'
    elif trade == 3:
      trade = 'USDT'
    else:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      currency = list[choose_num]
      market = '{0}-{1}'.format(trade, currency)
    except:
      print available
      white('\nGoing back to Main Menu')
      time.sleep(1)
      break
    try:
      values = r.hmget(market, 'Last', 'Bid', 'Ask')
      balance = api.getbalance(currency)
      last = float(values[0])
      bid = float(values[1])
      ask = float(values[2])
      white((30 * '-'))
      white('- Available:\t {0:.8f} {1}'.format(balance['Available'], currency))
      white('- Price (Last):  {0:.8f} {1}'.format(last, trade))
      white('- Price (Bid):\t {0:.8f} {1}'.format(bid, trade))
      white('- Price (Ask):\t {0:.8f} {1}'.format(ask, trade))
    except:
      white('Unable to retrieve data from redis.pontstrader.com')
      white('Going back to Main Menu')
      time.sleep(2)
      break
    for f in currencies:
      if f['Currency'] == currency:
        fee = f['TxFee']
        white('- Fee:\t\t {0:.8f} {1}'.format(fee, currency))
    for m in markets:
      if m['MarketCurrency'] == currency and m['BaseCurrency'] == trade:
        minimum = m['MinTradeSize']
        white('- Minimum ({0}): {1:.8f}'.format(currency, minimum))
    enough = balance['Available'] - fee
    if enough < 0.00000001:
      red('You dont have enough {0} ({1:.8f}) to sell anything!'.format(currency, enough))
      time.sleep(1)
      break
    else:
      green('You have {0:.8f} {1}'.format(balance['Available'], currency))
      white((30 * '-'))
      white('Sellprice?')
      yellow('1. Last ({0:.8f} {1})'.format(last, trade))
      yellow('2. Bid ({0:.8f} {1})'.format(bid, trade))
      yellow('3. Ask ({0:.8f} {1})'.format(ask, trade))
      yellow('4. Custom')
      red('5. Back to Main Menu') 
      try:
        sellprice = raw_input(Fore.WHITE+'Enter your choice [1-5] : ')
        sellprice = int(sellprice)
      except:
        white('\nInvalid number... going back to Main Menu')
        time.sleep(1)
        break
      if sellprice == 1:
        sell_for = last
        white('Selected \'Last\': {0:.8f} {1}'.format(last, trade))
      elif sellprice == 2:
        sell_for = bid
        white('Selected \'Bid\': {0:.8f} {1}'.format(bid, trade))
      elif sellprice == 3:
        sell_for = ask
        white('Selected \'Ask\': {0:.8f} {1}'.format(ask, trade))
      elif sellprice == 4:
        try:
          sell_for = raw_input(Fore.WHITE+'Sellprice? e.g. [0.00000001] : ')
          sell_for = float(sell_for)
          white('Selected \'Custom\': {0:.8f} {1}'.format(sell_for, trade))
        except:
          white('Please provide a proper sellprice! (e.g. {0:.8f})'.format(last))
          white('Going back to Main Menu')
          time.sleep(1)
          break
      elif sellprice == 5:
        break
      else:
        white('\nInvalid number... going back to Main Menu')
        time.sleep(1)
        break
    try:
      amount = raw_input(Fore.WHITE+'Amount? : ')
      amount = float(amount)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    white((30 * '-'))
    white('Selling {0:.8f} {1} for {2:.8f} {3} each, Proceed?'.format(amount, currency, sell_for, trade))
    green('1. yes')
    red('2. no (Back to Main Menu)')
    try:
      yes_no = raw_input(Fore.WHITE+'Enter your choice [1-2] : ')
      yes_no = int(yes_no)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if yes_no == 1:
      try:
        apicall = api.selllimit(market, amount, sell_for)
        sell_uuid = apicall['uuid']
        time.sleep(0.5)
        sellorder = api.getorder(uuid=sell_uuid)
        total = amount * sell_for
        green('Added a sell order for {0:.8f} {1} at {2:.8f} {3} each which is {4:.8f} {3} total'.format(amount, currency, sell_for, trade, total))
        white('Checking status in 2 seconds')
        time.sleep(2)
        if sellorder['IsOpen'] == False:
          white('Great! Order is completely filled')
        else:
          white('Order is not filled yet, would you like to wait up to 120 seconds?'.format(amount, sell_for, trade))
          green('1. yes')
          red('2. no (Back to Main Menu)')
          try:
            yes_no = raw_input(Fore.WHITE+'Enter your choice [1-2] : ')
            yes_no = int(yes_no)
          except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
          if yes_no == 1:
            yellow('Script will automatically return to Main Menu after 120 seconds')
            time_decrease = 120
            if sellorder['IsOpen'] == True:
              while sellorder['IsOpen'] == True:
                if time_decrease <= 0:
                  break
                yellow('Waiting until the sell order is completely filled! Remaining: {0:.8f} ({1} seconds remaining)'.format(sellorder['QuantityRemaining'], time_decrease))
                sellorder = api.getorder(uuid=sell_uuid)
                time.sleep(10)
                time_decrease -= 10
            white('Great! Order is completely filled')
          elif yes_no == 2:
            white('\nOk... going back to Main Menu')
            time.sleep(1)
            break
          else:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break
        white('Returning to Main Menu in 2 seconds...')
        time.sleep(2)
        break
      except:
        white('Bittrex API error: {0}'.format(apicall))
        white('Going back to Main Menu')
        time.sleep(2)
        break
    elif yes_no == 2:
      white('\nGoing back to Main Menu')
      time.sleep(1)
      break
    else:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
def white():
    print "LEDs WHITE"
    colors.white()
    return ('', 204)
Example #31
0
def withdraw(key, secret):
  
  import time, json, sys
  from pprint import pprint
  from time import gmtime, strftime
  from bittrex import bittrex
  from colors import white, red, green, yellow
  from colorama import Fore, Back, Style, init
  
  while True:
    try:
      api = bittrex(key, secret)
      currencies = api.getcurrencies()
    except:
      white('Bittrex API error: {0}'.format(api))
  
    white((30 * '-'))
    green('   W I T H D R A W')
    white((30 * '-'))
    yellow('NOTE: Make sure Withdraw is allowed for this API key')
    white((30 * '-'))
    try:
      balances = api.getbalances()
      green('Currency\tAvailable')
      number = 0
      list = []
      for coin in balances:
        available = coin["Available"]
        currency = coin["Currency"]
        if available != 0.0:
          number += 1
          list.append(currency)
          if len(currency) > 4:
            white('{0}. {1}\t{2:.8f}'.format(number, currency, available))
          else:
            white('{0}. {1}\t\t{2:.8f}'.format(number, currency, available))
    except:
      white('Bittrex API error: {0}'.format(balances))
      white('Going back to Main Menu')
      time.sleep(2)
    try:
      choose_num = raw_input(Fore.WHITE+'Enter your choice [1-{0}] : '.format(number))
      choose_num = int(choose_num)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      choose_num = choose_num - 1
      if choose_num == -1:
        white('Invalid number... going back to Main Menu')
        time.sleep(1)
        break
      for f in currencies:
        if f['Currency'] == list[choose_num]:
          fee = f['TxFee']
      green('Starting withdraw for {0}'.format(list[choose_num]))
      white((30 * '-'))
      balance = api.getbalance(list[choose_num])
      available = balance["Available"]
      white('Available: {0} {1}'.format(available, list[choose_num]))
      white('Fee:       {0} {1}'.format(fee, list[choose_num]))
      yellow('Fee will be calculated at the end, you may just withdraw the full amount.')
      white((30 * '-'))
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      quantity = raw_input(Fore.WHITE+'Quantity? : ')
      quantity = float(quantity)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if quantity > available:
      white('You can\'t withdraw more than available. Cancelled...')
      time.sleep(1)
      break
    try:
      address = raw_input(Fore.WHITE+'Withdraw Address? : ')
      address = str(address)
    except:
      white('Invalid input. Cancelled...')
      time.sleep(1)
      break
    try:
      paymentid = raw_input(Fore.WHITE+'Payment ID?' + Fore.YELLOW +' (If not required, leave empty)' + Fore.WHITE +' : ')
      paymentid = str(paymentid)
    except:
      white('Invalid input. Cancelled...')
      time.sleep(1)
      break
    white((30 * '-'))
    yellow('BITTREX NOTE: Please verify your withdrawal address. We cannot refund an incorrect withdrawal.')
    white((30 * '-'))
    if len(paymentid) > 0:
      green('You are about to withdraw {0:.8f} {1} to {2} with Payment ID {3}, is this correct?'.format(quantity, list[choose_num], address, paymentid))
    else:
      green('You are about to withdraw {0:.8f} {1} to {2}, is this correct?'.format(quantity, list[choose_num], address))
    green('1. yes')
    red('2. no (Back to Main Menu)')
    white((30 * '-'))
    try:
      yes_no = raw_input(Fore.WHITE+'Enter your choice [1-2] : ')
      yes_no = int(yes_no)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if yes_no == 1:
      try:
        if len(paymentid) > 0:
          apicall = api.withdraw(currency=list[choose_num], quantity=quantity, address=address, paymentid=paymentid)
        else:
          apicall = api.withdraw(currency=list[choose_num], quantity=quantity, address=address)
        print apicall['uuid']
        after_fee = quantity - fee
        if len(paymentid) > 0:
          green('Added a withdraw order for {0:.8f} {1} towards {2} with Payment ID {3} (incl. bittrex fee)'.format(after_fee, list[choose_num], address, paymentid))
        else:
          green('Added a withdraw order for {0:.8f} {1} towards {2} (incl. bittrex fee)'.format(after_fee, list[choose_num], address))
        white('Returning to Main Menu in 5 seconds...')
        time.sleep(5)
        break
      except:
        white('Bittrex API error: {0}'.format(apicall))
        white('Going back to Main Menu')
        time.sleep(2)
        break
    elif yes_no == 2:
      white('\nCancelled... going back to Main Menu')
      time.sleep(1)
      break
    else:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
Example #32
0
def trailing(key, secret, pushover_user, pushover_app, pushbullet_token,
             redis_password):

    import sys, os, json, time, threading, requests, redis
    from datetime import datetime
    from bittrex import bittrex
    from pushover import send_pushover
    from pushbullet import send_pushbullet
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    global messages

    try:
        messages
    except NameError:
        messages = {}
    else:
        pass

    white((40 * '-'))
    green('   T R A I L I N G  S T O P  L O S S')
    white((40 * '-'))
    while True:
        status_update = False
        gobuy = False
        try:
            threads = threading.enumerate()
            thread_counter = 0
            for t in threading.enumerate():
                if t.name.startswith('tsl-'):
                    thread_counter += 1
            if thread_counter > 0:
                yellow('There are currently {0} active tsl trade(s):'.format(
                    thread_counter))
            else:
                yellow('There are currently no active tsl trades')
            white(
                'Would you like to make another tsl trade or check the status/history of your tsl trades?'
            )
            green('1. New trade')
            yellow('2. Status / History')
            red('3. Back to Main Menu')
            try:
                yes_no = raw_input(Fore.WHITE + 'Enter your choice [1-3] : ')
                yes_no = int(yes_no)
                white((30 * '-'))
            except:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
            if yes_no == 1:
                pass
            elif yes_no == 2:
                while True:
                    try:
                        trades = 0
                        for k, v in messages.iteritems():
                            trades += 1
                            if v.startswith('tsl-'):
                                print v
                        if trades == 0:
                            red('There is currently no tsl trade status/history available!'
                                )
                            white((30 * '-'))
                        white('Refresh, new trade or back to Main Menu?')
                        green('1. Refresh')
                        yellow('2. New Trade')
                        red('3. Back to Main Menu')
                        go_break = False
                        try:
                            yes_no = raw_input(Fore.WHITE +
                                               'Enter your choice [1-3] : ')
                            yes_no = int(yes_no)
                            white((30 * '-'))
                        except:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                        if yes_no == 1:
                            pass
                        elif yes_no == 2:
                            break
                        elif yes_no == 3:
                            white('\nOk... going back to Main Menu')
                            time.sleep(1)
                            break
                        else:
                            go_break = True
                            white(
                                '\nInvalid number... going back to Main Menu')
                            time.sleep(1)
                            break
                    except:
                        red('\nUnable to retrieve active threads data... going back to Main Menu'
                            )
                        break
                if yes_no == 3 or go_break == True:
                    break
            elif yes_no == 3:
                white('\nOk... going back to Main Menu')
                time.sleep(1)
                break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                break
        except:
            red('\nUnable to retrieve active threads... there is something wrong please contact p0nts!'
                )
            break

        try:
            market = raw_input(
                Fore.WHITE + 'Market? (e.g. BTC-NEO / ETH-LTC / USDT-OMG) : ')
            market = str(market.upper())
            trade = market.split('-')[0]
            currency = market.split('-')[1]
            check_status = r.exists(market)
            if check_status != True:
                white('Unsupported market... going back to Main Menu')
                time.sleep(1)
                break
        except:
            white('\nInvalid input... going back to Main Menu')
            time.sleep(1)
            break

        try:
            value = raw_input(Fore.WHITE +
                              'How much {0}? (excl. fee) : '.format(trade))
            value = float(value)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break

        try:
            trailing = raw_input(Fore.WHITE +
                                 'Trailing percentage? (without %) : ')
            trailing = float(trailing)
        except:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break

        if market.startswith('BTC'):
            trade = 'BTC'
        elif market.startswith('ETH'):
            trade = 'ETH'
        elif market.startswith('USDT'):
            trade = 'USDT'
        else:
            white('Unsupported market... going back to Main Menu')
            time.sleep(1)
            break

        try:
            api = bittrex(key, secret)
            values = r.hmget(market, 'Ask', 'MarketName', 'BaseVolume',
                             'Volume', 'OpenBuyOrders', 'OpenSellOrders',
                             'High', 'Low', 'Last', 'Bid')
            available = api.getbalance(trade)
            price = float(values[0])
        except:
            white(
                'API error: Unable to retrieve pricing information... going back to Main Menu'
            )
            time.sleep(1)
            break

        if available['Available'] < 0.00100000:
            red('Not enough {0} to make a buy... going back to Main Menu'.
                format(trade))
            time.sleep(1)
            break

        white((40 * '-'))
        green('   M A R K E T  I N F O R M A T I O N')
        white((40 * '-'))
        yellow('- Market:           {0}'.format(market))
        yellow('- Volume:           {0:.8f}'.format(float(values[2])))
        yellow('- 24H volume:       {0:.8f}'.format(float(values[3])))
        yellow('- Open buy orders:  {0}'.format(values[4]))
        yellow('- Open sell orders: {0}'.format(values[5]))
        yellow('- 24H high:         {0:.8f}'.format(float(values[6])))
        yellow('- 24H low:          {0:.8f}'.format(float(values[7])))
        yellow('- Last:             {0:.8f}'.format(float(values[8])))
        yellow('- Ask:              {0:.8f}'.format(float(values[0])))
        yellow('- Bid:              {0:.8f}'.format(float(values[9])))
        white((40 * '-'))
        white('Proceed?')
        green('1. yes')
        red('2. no')
        try:
            proceed = raw_input(Fore.WHITE + 'Enter your choice [1-2] : ')
            proceed = int(proceed)
        except:
            white('\nCancelled... going back to Main Menu')
            time.sleep(1)
            break
        if proceed == 1:
            try:
                values = r.hmget(market, 'Ask', 'Bid')
                ask = float(values[0])
                bid = float(values[1])
                amount = float(value) / float(ask)
                orderbook = api.getorderbook(market, type='sell')
                orderbook_rate = orderbook[0]['Rate']
                orderbook_quantity = orderbook[0]['Quantity']
                if float(amount) < float(orderbook_quantity):
                    gobuy = True
                    break
                else:
                    while float(amount) > float(orderbook_quantity):
                        time.sleep(1)
                        orderbook = api.getorderbook(market, type='sell')
                        orderbook_rate = orderbook[0]['Rate']
                        orderbook_quantity = orderbook[0]['Quantity']
                        values = r.hmget(market, 'Ask', 'Bid')
                        ask = float(values[0])
                        bid = float(values[1])
                        amount = float(value) / float(ask)
                        yellow(
                            'Waiting for the volume to rise on lowest Ask to buy all for the same price.'
                        )
                    gobuy = True
                    break
            except:
                white(
                    'API error: Unable to create a buyorder... going back to Main Menu'
                )
                time.sleep(1)
                break
        elif proceed == 2:
            white('Ok... going back to Main Menu')
            time.sleep(1)
            break
        else:
            white('\nInvalid number... going back to Main Menu')
            time.sleep(1)
            break

    if gobuy == True:

        def start_thread(market, currency, amount, ask, trailing):
            time.sleep(1)
            global messages
            thread_name = threading.current_thread().name
            while True:
                try:
                    buy = api.buylimit(market, amount, ask)
                    time.sleep(0.5)
                    buy_uuid = buy['uuid']
                    time.sleep(0.5)
                    buyorder = api.getorder(uuid=buy_uuid)
                    push_send = False
                    while buyorder['IsOpen'] == True:
                        message = '{0}: Made a buyorder, waiting until it is filled! Remaining: {1:.8f} {2}'.format(
                            thread_name, buyorder['QuantityRemaining'],
                            currency)
                        messages[thread_name] = message
                        if push_send == False:
                            send_pushover(pushover_user, pushover_app, message)
                            send_pushbullet(pushbullet_token, message)
                            push_send = True
                        buyorder = api.getorder(uuid=buy_uuid)
                        time.sleep(10)
                    trailing_percentage = float(ask) / 100 * float(trailing)
                    trailing_stop_loss = float(ask) - float(
                        trailing_percentage)
                    stop_loss_percentage = '-{0:.2f}'.format(trailing)
                    buyprice = float(ask)
                    lastprice = 0
                except:
                    message = '{0}: API error: Was unable to create the buyorder... it was cancelled due to:\n{1}'.format(
                        thread_name, buy)
                    messages[thread_name] = message
                    send_pushover(pushover_user, pushover_app, message)
                    send_pushbullet(pushbullet_token, message)
                    break
                while float(ask) > float(trailing_stop_loss):
                    try:
                        time.sleep(0.5)
                        values = r.hmget(market, 'Ask')
                        ask = float(values[0])
                    except:
                        message = 'Unable to retrieve data from redis.pontstrader.com, trying to recover...'
                        messages[thread_name] = message
                    else:
                        percentage = 100 * (float(ask) -
                                            float(buyprice)) / float(buyprice)
                        trailing_percentage = float(ask) / 100 * float(
                            trailing)
                        if float(ask) > float(buyprice) and ask != lastprice:
                            if float(ask) > lastprice and float(ask) > float(
                                    buyprice):
                                new_trailing_stop_loss = float(ask) - float(
                                    trailing_percentage)
                                if float(new_trailing_stop_loss) > float(
                                        trailing_stop_loss):
                                    trailing_stop_loss = float(ask) - float(
                                        trailing_percentage)
                                    stop_loss_percentage = 100 * (
                                        float(trailing_stop_loss) -
                                        float(buyprice)) / float(buyprice)
                                    message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format(
                                        thread_name, currency, float(buyprice),
                                        float(ask), float(percentage),
                                        float(trailing_stop_loss),
                                        float(stop_loss_percentage))
                                    messages[thread_name] = message
                                else:
                                    message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format(
                                        thread_name, currency, float(buyprice),
                                        float(ask), float(percentage),
                                        float(trailing_stop_loss),
                                        float(stop_loss_percentage))
                                    messages[thread_name] = message
                            else:
                                message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format(
                                    thread_name, currency, float(buyprice),
                                    float(ask), float(percentage),
                                    float(trailing_stop_loss),
                                    float(stop_loss_percentage))
                                messages[thread_name] = message
                        elif float(ask) < float(buyprice) and float(
                                ask) != float(lastprice):
                            message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format(
                                thread_name, currency, float(buyprice),
                                float(ask), float(percentage),
                                float(trailing_stop_loss),
                                float(stop_loss_percentage))
                            messages[thread_name] = message
                        elif float(ask) == float(
                                buyprice) and float(ask) != float(lastprice):
                            pass
                        lastprice = float(ask)
                profit_percentage = 100 * (float(trailing_stop_loss) -
                                           float(buyprice)) / float(buyprice)
                try:
                    sell = api.selllimit(market, amount, trailing_stop_loss)
                    sell_uuid = sell['uuid']
                    time.sleep(0.5)
                    sellorder = api.getorder(uuid=sell_uuid)
                    while sellorder['IsOpen'] == True:
                        message = '{0}: Stop Loss triggered, waiting until the sell order is completely filled! Remaining: {1:.8f}'.format(
                            thread_name, sellorder['QuantityRemaining'])
                        messages[thread_name] = message
                        try:
                            sellorder = api.getorder(uuid=sell_uuid)
                        except:
                            pass
                        time.sleep(2)
                    message = '{0}: {1} SOLD | Buy price {2:.8f} | Sell price {3:.8f} | Profit {4:.2f}% (excl. fee)'.format(
                        thread_name, currency, buyprice, trailing_stop_loss,
                        profit_percentage)
                    messages[thread_name] = message
                    send_pushover(pushover_user, pushover_app, message)
                    send_pushbullet(pushbullet_token, message)
                    break
                except:
                    message = '{0}: API error: Was unable to create the sellorder... it was cancelled due to:\n{1}'.format(
                        thread_name, sell)
                    messages[thread_name] = message
                    send_pushover(pushover_user, pushover_app, message)
                    send_pushbullet(pushbullet_token, message)
                    break

        try:
            datetime = datetime.now().strftime("%d-%m-%Y.%H:%M:%S")
            threadname = 'tsl-{0}'.format(datetime)
            thread = threading.Thread(name=threadname,
                                      target=start_thread,
                                      args=(market, currency, amount, ask,
                                            trailing))
            thread.daemon = True
            thread.start()
            green(
                'Made a buy order, to check its status go to the Trailing Stop Loss menu again... going back to Main Menu in 2 seconds'
            )
            time.sleep(2)
        except:
            red('Unable to start thread... there is something wrong please contact p0nts!'
                )
Example #33
0
def watch(key, secret, redis_password):

    import time, json, sys, threading, redis
    from pprint import pprint
    from bittrex import bittrex
    from colors import white, red, green, yellow
    from colorama import Fore, Back, Style, init
    init()

    try:
        r = redis.Redis(host='redis.pontstrader.com',
                        port=6380,
                        db=0,
                        password=redis_password)
    except:
        white(
            'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...'
        )
        try:
            r = redis.Redis(host='redis2.pontstrader.com',
                            port=6380,
                            db=0,
                            password=redis_password)
        except:
            white(
                'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!'
            )

    class TestThread(threading.Thread):
        def __init__(self, name='Watch'):
            self._stopevent = threading.Event()
            self._sleepperiod = 1.0
            threading.Thread.__init__(self, name=name)

        def run(self):
            green('Starting watch for {0}'.format(market))
            yellow(
                'Checked every 0.5 seconds, only price/percentage changes will be shown'
            )
            yellow(
                'Price/Percentage changes are based on the moment the watch is started'
            )
            yellow(
                'Please note the Timestamp is taken from Bittrex, can be different then yours'
            )
            red('q+enter to return to Main Menu')
            lastprice = '0'
            try:
                values = r.hmget(market, 'Ask')
                start_price = float(values[0])
            except:
                white(
                    'Currency not available... or unable to retrieve data from redis.pontstrader.com'
                )
            else:
                while not self._stopevent.isSet():
                    try:
                        values = r.hmget(market, 'Ask', 'TimeStamp')
                        price = float(values[0])
                        timestamp = values[1]
                    except:
                        red('Unable to retrieve data from redis.pontstrader.com, trying to recover...'
                            )
                    else:
                        percent = 100 * (float(price) - float(start_price)
                                         ) / float(start_price)
                        if price != lastprice:
                            if percent < 0.00:
                                white(
                                    '{0} - The {1} price for 1 {2} is {3:.8f} {4}'
                                    .format(timestamp, trade, currency, price,
                                            trade) +
                                    (Fore.RED + ' ({0:.2f})%'.format(percent)))
                                lastprice = price
                            elif percent > 0.00:
                                white(
                                    '{0} - The {1} price for 1 {2} is {3:.8f} {4}'
                                    .format(timestamp, trade, currency, price,
                                            trade) +
                                    (Fore.GREEN +
                                     ' ({0:.2f})%'.format(percent)))
                                lastprice = price
                            else:
                                white(
                                    '{0} - The {1} price for 1 {2} is {3:.8f} {4} ({5:.2f}%)'
                                    .format(timestamp, trade, currency, price,
                                            trade, percent))
                                lastprice = price
                        time.sleep(0.5)
                    self._stopevent.wait(self._sleepperiod)
                white('Returning to Main Menu')

        def join(self, timeout=None):
            self._stopevent.set()
            threading.Thread.join(self, timeout)

    if __name__ == "watch":
        proceed = False
        while True:
            white((30 * '-'))
            green('   W A T C H')
            white((30 * '-'))
            white('Market?')
            yellow('1. BTC')
            yellow('2. ETH')
            yellow('3. USDT')
            red('4. Back to Main Menu')
            try:
                trade = raw_input(Fore.WHITE + 'Enter your choice [1-4] : ')
                trade = int(trade)
            except:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                proceed = False
                break
            if trade == 1:
                trade = 'BTC'
            elif trade == 2:
                trade = 'ETH'
            elif trade == 3:
                trade = 'USDT'
            elif trade == 4:
                proceed = False
                break
            else:
                white('\nInvalid number... going back to Main Menu')
                time.sleep(1)
                proceed = False
                break
            currency = raw_input(
                Fore.WHITE +
                'Currency? (examples: LTC / NEO / OMG) : ').upper()
            market = '{0}-{1}'.format(trade, currency)
            proceed = True
            break

        if proceed == True:
            testthread = TestThread()
            testthread.start()
            while True:
                exit = raw_input(Fore.RED +
                                 '\nq+enter to return to Main Menu\n')
                if exit == 'q':
                    testthread.join()
                    break