Example #1
0
 def post():
     content = request.get_json(silent=True)
     print(content)
     Database.insert_one(collection="user", data=content)
     print(content['email'])
     Iq = IQ_Option(content['email'], content['password'])
     Iq.connect()
     res = Iq.get_balance()
     print(res)
     return res
Example #2
0
def main():
    logs.print_message("Bot Started!")

    #login
    logs.print_message("Login Credentials IQ Option:")
    email = input("Email:")
    password = input("Pass:"******"Error on try to login. Check iq option credentials on environment variables.")
        exit()
    logs.print_message("Conected: IQ Option!")

    #stops
    #REAL / PRACTICE
    account_type = input("Set the account type (REAL or PRACTICE):")
    api.change_balance(account_type)
    original_balance = api.get_balance()
    logs.print_message("Original balance: $ {}".format(original_balance))
    stop_loss = input("Set a stop loss value:")
    stop_win = input("Set a stop win value:")

    #read trades
    f = open("trades.csv")
    csv_f = csv.reader(f)
    counter = 0
    for row in csv_f:
        if counter == 0:
            logs.print_message("Programming Orders...")
        else:
            start_time = datetime.datetime.strptime(row[1], '%H:%M')
            time_result = start_time - datetime.timedelta(seconds=15)
            add_option(row[0].replace('/', ''), time_result.strftime("%H:%M:%S"), row[2], row[3], stop_loss, stop_win, api, original_balance)
        counter = counter + 1

    logs.print_message("\nProcessing Orders...")

    while True:
        schedule.run_pending()
        time.sleep(1)
class IQOption:
    def __init__(self, email, senha):
        super().__init__()
        self.email = email
        self.senha = senha
        self.api = IQ_Option(self.email, self.senha)

    def definirConfiguracoes(self, ativo, timeframe, posicao):
        self.ativo = ativo
        self.timeframe = int(timeframe)
        self.posicao = int(posicao)

    def efetuarLogin(self):
        self.conectado, erro = self.api.connect()
        if self.conectado == False:
            logging.error(
                "Erro ao tentar entrar na conta IQ Option -> {}".format(
                    str(erro)))
            return False
        else:
            logging.info("Sucesso ao entrar na conta IQ Option")
            return True

    def checarAtivo(self, ativo):
        ativos = self.api.get_all_open_time()
        if ativos["digital"][ativo]["open"]:
            logging.info("Ativo encontrado")
            return True
        else:
            logging.error("O ativo {} nao foi encontrado".format(str(ativo)))
            return False

    def contaReal(self):
        self.api.change_balance("REAL")

    def contaDemo(self):
        self.api.change_balance("PRACTICE")

    def pegarSaldo(self):
        return self.api.get_balance()

    def pegarMoeda(self):
        return self.api.get_currency()

    def setEntrada(self, entrada):
        try:
            entrada = float(entrada)
        except:
            logging.error("Nao foi possivel definir o preco de entrada")
            return False
        if isinstance(entrada, float):
            self.entrada = entrada
            return True
        else:
            logging.error("Nao foi possivel definir o preco de entrada")
            return False

    def copiarEntradas(self):
        tempo = "PT{}M".format(str(self.timeframe))
        self.api.subscribe_live_deal("live-deal-digital-option", self.ativo,
                                     tempo, 10)
        entradas = self.api.get_live_deal("live-deal-digital-option",
                                          self.ativo, tempo)
        while True:
            time.sleep(3)
            entradas = self.api.get_live_deal("live-deal-digital-option",
                                              self.ativo, tempo)
            if len(entradas) >= 1:
                usuario = self.api.pop_live_deal("live-deal-digital-option",
                                                 self.ativo, tempo)
                posicao = self.api.request_leaderboard_userinfo_deals_client(
                    usuario["user_id"], usuario["country_id"])
                nome = str(usuario["name"])
                posicao = posicao["result"]["entries_by_country"]["0"][
                    "position"]
                acao = usuario["instrument_dir"]
                if posicao <= int(self.posicao):
                    print("Abriu ordem: {} ({} mundial) -> {}".format(
                        nome, str(posicao), acao.upper()))
                    _, ordem_id = self.api.buy_digital_spot(
                        self.ativo, self.entrada, acao, self.timeframe)
                    if ordem_id != "error":
                        while True:
                            verificar_ordem, ganhou = self.api.check_win_digital_v2(
                                ordem_id)
                            if verificar_ordem == True:
                                break
                        if ganhou < 0:
                            logging.info("---> Voce perdeu {}{}".format(
                                str(self.pegarMoeda()),
                                str(round(abs(ganhou), 2))))
                            print("---> Você perdeu {}{}".format(
                                str(self.pegarMoeda()),
                                str(round(abs(ganhou), 2))))
                        else:
                            logging.info("---> Voce ganhou {}{}".format(
                                str(self.pegarMoeda()),
                                str(round(abs(ganhou), 2))))
                            print("---> Você ganhou {}{}".format(
                                str(self.pegarMoeda()),
                                str(round(abs(ganhou), 2))))
                    else:
                        logging.error("Nao foi possivel abrir uma ordem")
                        print("---> Não foi possivel abrir uma ordem")
                else:
                    logging.info("Deixou passar: {} ({} mundial) -> {}".format(
                        nome, str(posicao), acao.upper()))
                    print("Deixou passar: {} ({} mundial) -> {}".format(
                        nome, str(posicao), acao.upper()))
Example #4
0
        '%Y-%m-%d %H:%M:%S')
    hora = hora.replace(tzinfo=tz.gettz('GMT'))

    return str(hora.astimezone(tz.gettz(
        'America/Sao Paulo')))[:-6] if retorno == 1 else hora.astimezone(
            tz.gettz('America/Sao Paulo'))


x = perfil()
print(
    "Nome: ",
    (x['name']),
)
print(
    "Balanço atual: ",
    (API.get_balance()),
)


def banca():
    return API.get_balance()


def payout(par, tipo, timeframe=1):
    if tipo == 'turbo':
        a = API.get_all_profit()
        return int(100 * a[par]['turbo'])

    elif tipo == 'digital':

        API.subscribe_strike_list(par, timeframe)
Example #5
0
from iqoptionapi.stable_api import IQ_Option
I_want_money = IQ_Option("username", "password")
I_want_money.connect()

I_want_money.buy(10, "EURUSD", "call", 10)
print('sss', I_want_money.get_balance())

# Follow  this url  to make  trade in  iq  logic  in case of long term forex trading
# https://libraries.io/pypi/iqoption-stable-api
Example #6
0
                            round(Decimal(operation.profit), 2), AMOUNT))

    if len(digitals) > 0:
        procs = []
        for digital in digitals:
            proc = Process(target=single_operation, args=(digital, ))
            procs.append(proc)
            proc.start()
    else:
        print('No operations at this time')


if __name__ == "__main__":
    last_hour, last_minute = read_file()
    if len(OPERATIONS) > 0:
        INITIAL_BALANCE = API.get_balance()
        print('Stop win: {}'.format(STOP_WIN))
        print('Initial {} balance: {}'.format(ACCOUNT, INITIAL_BALANCE))
        while True:
            now = datetime.now()
            if ((now.minute + 1) % CYCLE_DURATION) == 0 and (
                    now.second == 39 or now.second == 40):
                tic = time.perf_counter()
                operate()
                toc = time.perf_counter()
                time_to_sleep = CYCLE_DURATION * 60 - (toc - tic)
                time.sleep(time_to_sleep - 10)
                balance_now = API.get_balance()
                print(balance_now)
                now = datetime.now()
                if balance_now >= STOP_WIN:
Example #7
0
def run(choice_market):
    I_want_money = IQ_Option(ID + "@gmail.com", PW)
    I_want_money.connect()
    # I_want_money.change_balance('PRACTICE')
    I_want_money.change_balance('REAL')
    start_balance = I_want_money.get_balance()

    print('Account: %s , balance: %s' % (ID, start_balance))
    start_time = datetime.fromtimestamp(I_want_money.get_server_timestamp() + 3600 * 8)
    print(start_time)

    final = False
    loose_count = 0
    win_count = 0
    loose_times = 0
    running = True
    count = 0
    Money = 1
    MAXBET = 0
    ACTION = "put"
    ACTIVES=''
    value = ''
    count_put = 0
    count_call = 0
    # bet times
    global timess, Max_bet_amount_limit_set
    times = int(timess)
    Max_bet_amount_limit = int(Max_bet_amount_limit_set)


    # 計算當前profits的倍率
    max_open_market = {}
    open_market = []

    def append_market_to_choice():
        global ALL_Asset
        global d
        ALL_Asset = I_want_money.get_all_open_time()
        d = I_want_money.get_all_profit()
        # store open market in d=[]
        for market, value in d.items():
            for type, profit in value.items():
                if type == 'turbo':
                    choice[market] = profit
                    pass
        # print(choice)
        for market_key in list(choice):
            if ALL_Asset["turbo"][market_key]["open"] != True:
                del choice[market_key]
        # print(choice)
        for _ in range(3):
            max_market = max(choice, key=choice.get)
            max_open_market.update({max_market: choice[max_market]})
            del choice[max_market]
        for x in max_open_market.keys():
            open_market.append(x)

        print(max_open_market)
        # print(open_market)

    append_market_to_choice()

    # 每隔一個時段檢查現在市場的profits是否正確。
    def check_market_status(number):
        global ALL_Asset
        global d
        ALL_Asset = I_want_money.get_all_open_time()
        d = I_want_money.get_all_profit()
        # store open market in d=[]
        for market, value in d.items():
            for type, profit in value.items():
                if type == 'turbo':
                    choice[market] = profit
                    pass
        # print(choice)
        for market_key in list(choice):
            if ALL_Asset["turbo"][market_key]["open"] != True:
                del choice[market_key]

        number = number - 1
        a = open_market[number]
        # print(a)
        for key, value in max_open_market.items():
            # print(key)
            if key == a:
                if choice.get(a) == value:
                    return True
                else:
                    return False

    # high profits
    def cal_profits_multiple(profits):
        if profits <= 0.7:
            x = 1 / profits
            x = x + 1
        else:
            x = 2 / profits

        return round(x, 3)


    def find_max_profit_market(number):
        number = number - 1
        a = open_market[number]
        # print(a)
        for key, value in max_open_market.items():
            # print(key)
            if key == a:
                b = value
                return a, b

    # check order ID win or loose
    def check_order_info():
        check_id = True
        # c_count 檢查是否有市場重複下單,若有則重新尋找新的市場
        c_count = 1
        while check_id:
            results = I_want_money.get_optioninfo(5)
            results = results.get('msg')
            results = results.get('result')
            results = results.get('closed_options')
            # results[number] is 查找最近第幾筆歷史交易紀錄
            results0 = results[0]
            results1 = results[1]
            results2 = results[2]

            if [id_list_1[1]][0] in results0.get('id'):
                check_id = False
                results = results0
            elif [id_list_1[1]][0] in results1.get('id'):
                check_id = False
                results = results1
            elif [id_list_1[1]][0] in results2.get('id'):
                check_id = False
                results = results2

        print('=====' * 20)


        if results['amount'] == results['win_amount']:
            print('results : equal')
            print('done..')
            print('=====' * 20)
            return 'equal'
        else:
            print('results : %s' % results['win'])
            print('done..')
            print('=====' * 20)
            return results['win']


    def check_order_results(value, loose_count, loose_times, Money, multiple, Max_bet_amount_limit, times, ACTION,
                            win_count, running, count_call, count_put, profit):

        if value == 'loose':
            # count loose 次數
            loose_count = loose_count + 1
            loose_times = loose_times + 1

            if ACTION == 'put':
                count_call = count_call+1
            else:
                count_put = count_put+1
            Money = format(Money * multiple, '.3f')
            # 限制 Max_bet_amount_limit 最大下注金額,超過MAXBET金額則離開
            if float(Money) >= Max_bet_amount_limit:
                # running = False
                print('Now betAmount:', Money, '$ is too large, please STOP!!!!')
                Money = 1


            # 測試最後一次是否win?,若是loose且 < MAXBET,則for loop繼續直到獲勝結束
            if x == times - 1:
                times = 2
                # if loose_times == 5 or loose_times == 8:
                #     sleep(57)
                if ACTION == "put":
                    ACTION = "call"
                else:
                    ACTION = "put"

            else:
                if ACTION == "put":
                    ACTION = "call"
                else:
                    ACTION = "put"

        elif value == 'win':
            loose_times = 0
            win_count = win_count + 1

            if ACTION == 'call':
                count_call = count_call+1
            else:
                count_put = count_put+1

            # if x == times -1 --> 如果最後一次win 則離開迴圈完成running
            if x == times - 1:
                running = False
            else:
                Money = 1
        # if equals
        else:
            if x == times - 1:
                times = 2
        # 每兩分鐘下單一次,無論輸贏

        print('win: %s , loose: %s' % (win_count, loose_count))
        return loose_count, loose_times, Money, multiple, Max_bet_amount_limit, times, ACTION, win_count, running, count_call, count_put

    # 自動下單,每次整點下單
    try:
        while True:
            times = times + 1
            print('=====' * 20)
            print('Start....')
            ACTIVES, profit = find_max_profit_market(choice_market)
            multiple = float(format(cal_profits_multiple(profit), '.2f'))
            print('Now Trading market:[%s], Profit: %s , Multiple: %s' % (ACTIVES, profit, multiple))
            firstBet = True
            while running:
                from multiprocessing import Lock
                lock = Lock()
                for x in range(1, times):
                    count = count + 1
                    print('\n')
                    print('Start...')
                    print('ROUND : %s' % count)
                    timestamp = I_want_money.get_server_timestamp()
                    dt_object = datetime.fromtimestamp(timestamp)
                    dt_object = dt_object.second
                    print('=====' * 20)
                    wait = 60
                    wait = wait - dt_object
                    if float(Money) <= Max_bet_amount_limit:
                        if firstBet:
                            print('ready... BetAmount : ', Money)
                            print('wait %d sec to order' % wait)
                            if dt_object >= 55:
                                sleep(57)
                                pass
                            else:
                                sleep(wait - 2)
                                pass
                            firstBet = False
                        else:
                            print('ID matching...')

                            print('ready...   BetAmount : %s $' % Money)
                            print('\n')
                    else:
                        return win_count, loose_count, MAXBET, Max_bet_amount_limit

                    print('order..   direction:', ACTION)
                    # expirations_mode :0 為turbo
                    expirations_mode = 0
                    Money = float(Money)

                    # 下單
                    lock.acquire()
                    id_list_1 = I_want_money.buy(Money, ACTIVES, ACTION, expirations_mode)
                    lock.release()
                    print(id_list_1)

                    # 紀錄MAXBET
                    if Money > MAXBET:
                        MAXBET = Money

                    if id_list_1[1]:
                        print("check result only  id : %s" % id_list_1[1])
                    else:
                        pass

                    # check trading market & profits info
                    if x % 5 == 0:
                        if check_market_status(choice_market):
                            print('good market to be continue...')
                            pass
                        else:
                            append_market_to_choice()
                            ACTIVES, profit = find_max_profit_market(choice_market)
                            multiple = float(format(cal_profits_multiple(profit), '.2f'))
                            print('\n')
                            print('Time to check marketing info ')
                            print('Now Trading market:[%s], Profit: %s , Multiple: %s' % (ACTIVES, profit, multiple))

                    # get value = win or loose

                    while True:
                        I_want_money.connect()
                        if id_list_1[0] == True:
                            value = check_order_info()
                        # value = 'win'
                        elif id_list_1[0] == False:
                            while True:
                                lock.acquire()
                                id_list_1 = I_want_money.buy(Money, ACTIVES, ACTION, expirations_mode)
                                lock.release()
                                if id_list_1[0] == True:
                                    print("afresh check result only  id : %s" % id_list_1[1])
                                    value = check_order_info()
                                    if value == 'win' or value == 'loose' or value == 'equal':
                                        break

                        if value == 'win' or value == 'loose' or value == 'equal':
                            break


                    print('check order results...')
                    lock.acquire()
                    loose_count, loose_times, Money, multiple, Max_bet_amount_limit, times, ACTION, win_count, running, count_call, count_put = check_order_results(
                        value, loose_count, loose_times, Money, multiple, Max_bet_amount_limit, times, ACTION, win_count, running, count_call, count_put, profit)
                    lock.release()
                    if running == False:
                        break
            final = True
            break
    finally:
        if final:
            print('finish..')
        else:
            print('This processing has something wrong then terminal, now trading market is ', ACTIVES)

        # results info with running time , profits
        end_time = datetime.fromtimestamp(I_want_money.get_server_timestamp() + 3600 * 8)

        print('Start time %s' % start_time)
        print('Finish time %s' % end_time)
        print('Max Bet Amount:', MAXBET, '$')

        total_running_time = end_time - start_time
        print('Total Running Time:%s' % total_running_time)
        rate = win_count / (win_count + loose_count)
        rate = format(float(rate) * 100, '.2f')
        print('Rate: %s ' % rate)
        # time need change type to string data
        start_time = str(start_time)
        end_time = str(end_time)
        total_running_time = str(total_running_time)
        rate = float(rate)
        p_row = [start_time, end_time, total_running_time, MAXBET,
               Max_bet_amount_limit, win_count, loose_count, rate]
        print(p_row)

        return win_count, loose_count, MAXBET, Max_bet_amount_limit
Example #8
0
class API:
    def __init__(self,
                 paridade='',
                 valor=2,
                 expiracao='',
                 direcao='',
                 tipo='',
                 email='*****@*****.**',
                 senha='Teste123'):
        self.paridade = paridade
        self.valor = int(valor)
        self.senha = senha
        self.expiracao = expiracao
        self.action = 'call' if direcao == 'CIMA' else 'put'
        self.email = email
        self.tipo = tipo
        self.api = None

        print(self.email, self.senha)

    def connect(self):
        self.api = IQ_Option(self.email, self.senha)
        check, reason = self.api.connect()
        self.api.change_balance("PRACTICE")
        print(check, "\n", reason)
        # print(self.api.check_connection())

    def paridades(self):
        assets = self.api.get_all_open_time()
        binary = []
        digital = []
        for asset in assets["binary"]:
            if assets["binary"][asset]["open"]:
                binary.append(asset)

        for asset in assets["digital"]:
            if assets["digital"][asset]["open"]:
                digital.append(asset)

        return binary, digital

    def connect_and_buy(self, email, senha, paridade, price, direcao,
                        expiracao, tipo):
        conta = IQ_Option(email, senha)
        check, reason = conta.connect()
        conta.change_balance("PRACTICE")
        print(check, reason)

        action = 'call' if direcao == 'CIMA' else 'put'
        valor = int(price)
        expiracao = int(expiracao)

        if (tipo == 'BINÁRIA'):
            check, id = conta.buy(valor, paridade, action, expiracao)
            if check:
                print('ordem aberta')
        if (tipo == 'DIGITAL'):
            print('digital')
            check, id = conta.buy_digital_spot(paridade, valor, action,
                                               expiracao)
            if check:
                print("ordem aberta")
        return check

    def balance(self):
        self.api.change_balance('REAL')
        return self.api.get_balance()

    def buy(self):
        print(self.action, self.valor, self.paridade, self.expiracao)

        if (self.tipo == 'BINÁRIA'):
            check, id = self.api.buy(self.valor, self.paridade, self.action,
                                     self.expiracao)
            if check:
                print('ordem aberta')
        if (self.tipo == 'DIGITAL'):
            print('digital')
            check, id = self.api.buy_digital_spot(self.paridade, self.valor,
                                                  self.action, self.expiracao)
            if check:
                print("ordem aberta")
        return check
Example #9
0
print('conecting ...')
print(API.check_connect)
API.change_balance(MODE)


def getProfile(API):
    perfil = json.loads(json.dumps(API.get_profile_ansyc()))
    return perfil


profile = getProfile(API)
print(profile['name'])
print(profile['last_name'])
print(profile['email'])
print(profile['currency'])
print(API.get_balance())

par = 'EURUSD-OTC'
entrada = 12
direcao = 'call'
timeframe = 1

status, id = API.buy(entrada, par, direcao, timeframe)

print(status)
print(id)

if status:
    lucro = API.check_win_v3(id)
    print(' LUCRO: ' + str(lucro))
Example #10
0
                                              direcao_sinal_entrada,
                                              tempo_sinal_entrada)
            exit()

#Teste da API
if input_inicial == 'teste' or input_inicial == 'TESTE':
    API = IQ_Option(config['login'], config['senha'])
    API.connect()
    API.change_balance('PRACTICE')

    #Mudar configurações pra fazer o teste
    ativo_checkwin = 'EURUSD'
    hora_checkwin = '2020-05-09 23:28:00'
    direcao_checkwin = 'call'
    lucro = 10
    balance = API.get_balance()
    currency = API.get_currency()
    print(
        '--------------------------------------------------------------------------------\n                                Ativo: '
        + str(ativo_checkwin) + '\n                          Hora: ' +
        str(hora_checkwin) + '\n                                Direção: ' +
        str(direcao_checkwin) +
        '\n--------------------------------------------------------------------------------\n                                   WIN GALE\n                                  LUCRO: '
        + str(round(lucro, 2)) + '\n                              Saldo: ' +
        str(round(float(balance), 2)),
        str(currency) +
        '\n--------------------------------------------------------------------------------'
    )

    while True:
        hora1 = API.get_server_timestamp()
Example #11
0
    def login_iq(self):
        def stop_run():
            self.plainTextEdit.appendPlainText("หยุดทำงาน!")
            while True:
                QtCore.QCoreApplication.processEvents()

        def mack_up():
            self.plainTextEdit.appendPlainText("เริ่มทำงาน!")
            profit = 0.0
            wins = 0
            loss = 0
            RMG = 0
            ATM = self.lineEdit_4.text()
            MAXMG = self.lineEdit_5.text()
            XMG = self.lineEdit_3.text()
            TP = self.lineEdit_6.text()
            SL = self.lineEdit_7.text()
            while True:
                QtCore.QCoreApplication.processEvents()
                if ATM == "":
                    while ATM == "":
                        QtCore.QCoreApplication.processEvents()
                        self.plainTextEdit.appendPlainText(
                            "กรุณาเช็คการตั้งค่าจำนวนเงิน!")
                        if ATM != "":
                            ATM = self.lineEdit_4.text()
                            break
                if TP != "":
                    if float(profit) >= float(TP):
                        self.plainTextEdit.appendPlainText(
                            "ยินดีด้วยถึง TP ที่กำหนด!")
                        stop_run()
                if SL != "":
                    if float(profit) <= (float(SL) * -1.00):
                        print(SL)
                        self.plainTextEdit.appendPlainText(
                            "รอบหน้าเอาใหม่ถึง SL ที่กำหนด!")
                        stop_run()

                TMIQ = API.get_server_timestamp()
                FMTMIQ = datetime.fromtimestamp(TMIQ)
                DOTC = (FMTMIQ.strftime("%w"))
                RDOD = random.choices(["call", "put"])
                OD = (RDOD[0])
                while True:
                    QtCore.QCoreApplication.processEvents()
                    chop1 = API.get_all_open_time()
                    if DOTC == 5 or DOTC == 0 or (
                            chop1["digital"]["USDJPY-OTC"]["open"]) == True:
                        RDCA = random.choices([
                            "USDJPY-OTC", "EURJPY-OTC", "USDCHF-OTC",
                            "EURUSD-OTC", "AUDCAD-OTC", "GBPUSD-OTC",
                            "GBPJPY-OTC", "EURGBP-OTC"
                        ])
                        CA = (RDCA[0])
                        chop2 = (chop1["digital"][CA]["open"])
                        if chop2 == True:
                            break
                    elif (chop1["digital"]["USDJPY"]["open"]) == True:
                        RDCA = random.choices([
                            "USDJPY", "EURJPY", "USDCHF", "EURUSD", "AUDCAD",
                            "GBPUSD", "GBPJPY", "EURGBP"
                        ])
                        CA = (RDCA[0])
                        chop2 = (chop1["digital"][CA]["open"])
                        if chop2 == True:
                            break
                    else:
                        RDCA = random.choices([
                            "USDJPY", "EURJPY", "USDCHF", "EURUSD", "AUDCAD",
                            "GBPUSD", "GBPJPY", "EURGBP"
                        ])
                        CA = (RDCA[0])
                        chop2 = (chop1["digital"][CA]["open"])
                        if chop2 == True:
                            break
                while True:
                    QtCore.QCoreApplication.processEvents()
                    TMIQ = API.get_server_timestamp()
                    FMTMIQ = datetime.fromtimestamp(TMIQ)
                    if FMTMIQ.second <= 5:
                        if ATM == "":
                            while ATM == "":
                                QtCore.QCoreApplication.processEvents()
                                self.plainTextEdit.appendPlainText(
                                    "กรุณาเช็คการตั้งค่าจำนวนเงิน!")
                                ATM = self.lineEdit_4.text()
                        if int(ATM) < 1:
                            ATM = 1
                        order_iq, id = (API.buy_digital_spot(
                            CA, float(ATM), OD, 1))
                        if order_iq == True:
                            show_opod = ("ออก Order" + (" ") + str(CA))
                            self.plainTextEdit.appendPlainText(show_opod)
                            while True:
                                QtCore.QCoreApplication.processEvents()
                                check, win = API.check_win_digital_v2(id)
                                if check == True:
                                    break
                            if win > 0:
                                wins = wins + 1
                                RMG = 0
                                ATM = self.lineEdit_4.text()
                                profit = profit + win
                                show_rs = ("ชนะ" + str(" ") +
                                           str("%.2f" % win))
                                self.plainTextEdit.appendPlainText(show_rs)
                                self.label_4.setNum(float("%.2f" % profit))
                                self.label_7.setNum(wins)
                                break

                            else:
                                loss = loss + 1
                                RMG = RMG + 1
                                if MAXMG != "":
                                    ATM = float(ATM) * float(XMG)
                                    if RMG > int(MAXMG):
                                        ATM = self.lineEdit_4.text()

                                profit = profit + win
                                show_rs = ("แพ้" + str(" ") +
                                           str("%.2f" % win))
                                self.plainTextEdit.appendPlainText(show_rs)
                                self.label_4.setNum(float("%.2f" % profit))
                                self.label_9.setNum(loss)
                                break
                        else:
                            show_opod = ("ออก Order ไม่สำเร็จ!" + (" ") +
                                         str(CA))
                            self.plainTextEdit.appendPlainText(show_opod)
                            break
                    else:
                        show_st = ("รอเวลา...:" + str(FMTMIQ.second) +
                                   str(":") + str(CA) + str(":") + str(OD))
                        self.plainTextEdit.appendPlainText(show_st)

        user = self.lineEdit.text()
        password = self.lineEdit_2.text()
        API = IQ_Option(user, password)
        iqch1, iqch2 = API.connect()
        if iqch1 == True:
            self.label_5.setText("ล็อคอินสำเร็จ!")
            mode = self.comboBox.currentText()
            API.change_balance(mode)
            BA = API.get_balance()
            self.label_2.setNum(BA)
            self.pushButton_2.clicked.connect(mack_up)
            self.pushButton_3.clicked.connect(stop_run)
        else:
            self.label_5.setText("ล็อคอินไม่ผ่าน!")
import time
from iqoptionapi.stable_api import IQ_Option
iqEmail = "your iq options email"
iqPass = "******"
iqo = IQ_Option(iqEmail, iqPass)
iqo.connect()  #connect to iqoption
profit = 0.0
loss = 0
cntr = 0
mode = "PRACTICE"
#mode = "REAL"
iqo.change_balance(mode)
balance = (iqo.get_balance())
currency = (iqo.get_currency())
print("Balance : " + str(balance))
market = "EURUSD"
amount = 1
dur = 1
act = "put"

while True:
    pps, ids = iqo.buy_digital_spot(market, amount, act, dur)
    print "trade started wait for 60 seconds"
    if ids != "error":
        while True:
            check, win = iqo.check_win_digital_v2(ids)
            if check == True:
                break
        if win < 0:
            loss = loss + 1
            print("lost")
Example #13
0
        return d


# Carrega as configuracoes
config = configuracao()

# Exibindo os dados iniciais
print(Fore.YELLOW + '\n --> Seus Dados')
print('Nome:', x['name'])
TConta = API.get_balance_mode()
if TConta == 'PRACTICE':
    print('Conta de Treinamento')
if TConta == 'REAL':
    print('Conta Real')
moeda = API.get_currency()
banca2 = API.get_balance()
if moeda == 'USD':
    print('Banca:', '$', banca2)
else:
    print('Banca:', 'R$', banca2)

print(Fore.YELLOW + '\n --> Dados das Operações')
print('Paridade Selecionada:', str(config['paridade']))
if config['op_digital'] == 'S' and config['op_binario'] == 'N':
    print('Operar em: Digital')
elif config['op_binario'] == 'S' and config['op_digital'] == 'N':  # BINARIO
    print('Operar em: Binário')
print('TimeFrame:', str(config['timeframe']), 'M')
if moeda == 'USD':
    print('Valor de Entrada:', '$', str(config['valor_entrada']))
else:
Example #14
0
class IQOption:
    def __init__(self,
                 goal,
                 size,
                 maxdict,
                 money,
                 expiration_mode,
                 account='PRACTICE'):
        '''
        account : ['REAL', 'PRACTICE']
        '''
        import json
        from iqoptionapi.stable_api import IQ_Option
        data = json.load(open('credentials.json'))
        username = data['email']
        password = data['password']
        self.Iq = IQ_Option(username, password)
        print()
        print('logging in...')
        check, reason = self.Iq.connect()  #connect to iqoption
        print('login:'******'SUCCESSFUL' if check else 'FAILED')
        print()
        assert check, True
        self.login_time = datetime.datetime.now()
        #self.Iq.reset_practice_balance()
        self.Iq.change_balance(account)
        ALL_Asset = self.Iq.get_all_open_time()
        if ALL_Asset["turbo"][goal]["open"]:
            goal = goal
        else:
            goal = goal + '-OTC'
        print('goal =', goal)

        self.goal = goal
        self.size = size
        self.maxdict = maxdict
        self.money = money
        self.expirations_mode = expiration_mode
        self.consecutive_error = 0
        self.forex_order_id = []
        instrument_type = 'forex'
        instrument_id = self.goal
        print('forex: leverage:',
              self.Iq.get_available_leverages(instrument_type, instrument_id))

        print()

        #self.test_forex()

    def buy(self, action, check_result):
        buy_success, buy_order_id = self.Iq.buy(self.money, self.goal, action,
                                                self.expirations_mode)
        #buy_success, buy_order_id = self.Iq.buy(int(self.get_balance()*0.1),self.goal,action,self.expirations_mode)
        if not check_result:
            return None, None
        if buy_success:
            #print(action,'success', end='\r')
            result, earn = self.Iq.check_win_v4(buy_order_id)
            self.consecutive_error = 0
            #print(' '*12, end='\r')
            return result, round(earn, 2)
        else:
            print(action + ' fail')
            self.consecutive_error += 1
            assert self.consecutive_error < 5, 'Failed more than 5 times'
            return None, None

    def get_candles(self):
        self.Iq.start_candles_stream(self.goal, self.size, self.maxdict)
        candles = self.Iq.get_realtime_candles(self.goal, self.size)
        self.Iq.stop_candles_stream(self.goal, self.size)

        candles = list(candles.values())
        d = [[c['open'], c['close'], c['min'], c['max']] for c in candles]
        data = pd.DataFrame(d, columns=['open', 'close', 'low', 'high'])
        #data = np.array(d)
        return data

    def get_balance(self):
        # current_balance = {'request_id': '', 'name': 'balances',
        # 'msg': [
        #   {'id': 414500451, 'user_id': 84068869, 'type': 1, 'amount': 0, 'enrolled_amount': 0, 'enrolled_sum_amount': 0, 'hold_amount': 0, 'orders_amount': 0, 'auth_amount': 0, 'equivalent': 0, 'currency': 'USD', 'tournament_id': None, 'tournament_name': None, 'is_fiat': True, 'is_marginal': False, 'has_deposits': False},
        #   {'id': 414500452, 'user_id': 84068869, 'type': 4, 'amount': 15023.81, 'enrolled_amount': 15023.811818, 'enrolled_sum_amount': 15023.811818, 'hold_amount': 0, 'orders_amount': 0, 'auth_amount': 0, 'equivalent': 0, 'currency': 'USD', 'tournament_id': None, 'tournament_name': None, 'is_fiat': True, 'is_marginal': False, 'has_deposits': False},
        #   {'id': 414500453, 'user_id': 84068869, 'type': 5, 'amount': 0, 'enrolled_amount': 0, 'enrolled_sum_amount': 0, 'hold_amount': 0, 'orders_amount': 0, 'auth_amount': 0, 'equivalent': 0, 'currency': 'BTC', 'tournament_id': None, 'tournament_name': None, 'is_fiat': False, 'is_marginal': False, 'has_deposits': False},
        #   {'id': 414500454, 'user_id': 84068869, 'type': 5, 'amount': 0, 'enrolled_amount': 0, 'enrolled_sum_amount': 0, 'hold_amount': 0, 'orders_amount': 0, 'auth_amount': 0, 'equivalent': 0, 'currency': 'ETH', 'tournament_id': None, 'tournament_name': None, 'is_fiat': False, 'is_marginal': False, 'has_deposits': False}
        # ], 'status': 0}
        # return self.Iq.get_balances()['msg'][1]['amount']
        return self.Iq.get_balance()

    def buy_forex(self, action, trail_stop=False):
        instrument_type = 'forex'
        instrument_id = self.goal
        side = action
        amount = 100
        #amount = round((self.get_balance() - 9668) * 0.1, 2)
        leverage = 50
        type = 'market'
        limit_price = None
        stop_price = None

        #stop_lose_kind = None
        #stop_lose_value = None
        take_profit_kind = None
        take_profit_value = None
        stop_lose_kind = 'percent'
        stop_lose_value = 1.0
        #take_profit_kind = 'percent'
        #take_profit_value = 1.0

        use_trail_stop = trail_stop
        auto_margin_call = False
        use_token_for_commission = False
        check, order_id = self.Iq.buy_order(
            instrument_type=instrument_type,
            instrument_id=instrument_id,
            side=side,
            amount=amount,
            leverage=leverage,
            type=type,
            limit_price=limit_price,
            stop_price=stop_price,
            stop_lose_value=stop_lose_value,
            stop_lose_kind=stop_lose_kind,
            take_profit_value=take_profit_value,
            take_profit_kind=take_profit_kind,
            use_trail_stop=use_trail_stop,
            auto_margin_call=auto_margin_call,
            use_token_for_commission=use_token_for_commission)

        self.forex_order_id.append(order_id)
        '''
        print('- '*10)
        print(self.Iq.get_order(order_id))
        print('- '*10)
        print(self.Iq.get_positions(instrument_type))
        print('- '*10)
        print(self.Iq.get_position_history(instrument_type))
        print('- '*10)
        print(self.Iq.get_available_leverages(instrument_type, instrument_id))
        print('- '*10)
        import time
        time.sleep(10)
        print(self.Iq.close_position(order_id))
        print('- '*10)
        print(self.Iq.get_overnight_fee(instrument_type, instrument_id))
        print('- '*10)
        '''

    def all_positions_closed_forex(self):
        all_close = True
        self.num_open_positions = 0
        for order_id in self.forex_order_id:
            order_type, order_status = self.get_position_forex(order_id)
            if order_status == 'open':
                self.num_open_positions += 1
                all_close = False
        return all_close

    def close_forex(self):
        self.Iq.close_position(self.forex_order_id)

    def close_all_forex(self):
        for order_id in self.forex_order_id:
            self.Iq.close_position(order_id)

    def get_position_forex(self, order_id):
        #return self.Iq.get_position(self.forex_order_id)[1]['position']['status']
        order = self.Iq.get_position(order_id)[1]['position']
        order_type = order['type']
        order_status = order['status']
        return order_type, order_status

    def test_forex(self):
        import time
        print('= ' * 20)
        self.buy_forex('sell')
        print(self.get_position_forex())
        print()
        time.sleep(5)
        self.close_forex()
        print(self.get_position_forex())
        print()
        print('= ' * 20)
        print()
        self.buy_forex('buy')
        print(self.get_position_forex())
        print()
        time.sleep(5)
        self.close_forex()
        print(self.get_position_forex())
        print()
        print('= ' * 20)

    def reconnect_after_10_minutes(self):
        b = datetime.datetime.now()
        #print((b-self.login_time).seconds, 'seconds')
        if (b - self.login_time).seconds > 60 * 10:
            check, reason = self.Iq.connect()  #connect to iqoption
            assert check, True
            #print(f'reconnected after {(b-self.login_time).seconds} seconds!')
            self.login_time = datetime.datetime.now()
Example #15
0
            if config['Lista'] == 'S':
                lista = leituraLista()
                t['Lista'] = threading.Thread(target=e.lista, args=())
                t['Lista'].start()
            #Carrega LOG
            print('####  BUSCANDO OPORTUNIDADES  ########')
            t['Lista'] = threading.Thread(target=printLog,
                                          args=(texto, logTransacao,
                                                logNaoAberto, config))
            t['Lista'].start()
        else:
            MinutoAtual = int(strftime("%M", localtime()))

            if tempMinAnterior != MinutoAtual:
                tempMinAnterior = MinutoAtual
                montanteAtual = API.get_balance()
                if config['StopGain'] <= montanteAtual:
                    print()
                    print(
                        '###### PARABENS STOP GAIN ########## \n TOTAL GANHO:',
                        montanteAtual)
                    logNaoAberto.append(
                        '###### PARABENS STOP GAIN ########## \n TOTAL GANHO:'
                        + str(montanteAtual))
                    logTransacao.append(
                        '###### PARABENS STOP GAIN ########## \n TOTAL GANHO:'
                        + str(montanteAtual))
                    config['continua'] = False
                    input('\n Aperte qualquer tecla para finalizar')

                elif config['StopLoss'] >= montanteAtual + config[
Example #16
0
            btc_buy_price2 = btc_buy_price - 400
            btc_new_price = 0
            btc_temp = 0
            time.sleep(120)

        elif date_now == '18:00':
            btc_buy_price = btc_new_price / btc_temp
            btc_buy_prie = btc_buy_price - 100
            btc_buy_price2 = btc_buy_price - 500
            btc_new_price = 0
            btc_temp = 0
            time.sleep(120)

        #busca o valor total de fundos na carteira
        print('5')
        wallet = Iq.get_balance()
        wallet_comprar = wallet / 2  #quantidade que ele ira comprar com base no valor total que a sua carteira esta no momento
        time.sleep(1)
        print('6')

        #buy btc if he is price valeu is lower that btc buy price
        if price_btc < btc_buy_price and wallet >= 20:
            print('7')
            amount = wallet_comprar  # seta o valor da compra como metade do valor da carteira

            check, id = Iq.buy_order(
                instrument_type=instrument_type,
                instrument_id=instrument_id,
                side=side,
                amount=amount,
                leverage=leverage,
    if len(OPERATIONS) > 0:
        API = IQ_Option(EMAIL, PASSWORD)
        API.set_max_reconnect(5)
        API.change_balance(ACCOUNT)

        while True:
            if API.check_connect() == False:
                print('Not connected')
                API.connect()
            else:
                print('{} account connected'.format(ACCOUNT))
                break

            time.sleep(1)

        INITIAL_BALANCE = API.get_balance()
        print('{} balance: {}'.format(ACCOUNT, INITIAL_BALANCE))

        while True:
            now = datetime.now()
            print(now)
            if ((now.minute + 1) % CYCLE_DURATION) == 0 and now.second == 40:
                print('Entrou')
                tic = time.perf_counter()
                operate()
                toc = time.perf_counter()
                time_to_sleep = CYCLE_DURATION * 60 - (toc - tic)
                print('Sleeping for {} minutes'.format(time_to_sleep / 60))
                time.sleep(time_to_sleep - 15)
            time.sleep(1)
Example #18
0
# allow unlimited reconnect, (_) number of reconnection.
iq.set_max_reconnect(-1)
# Check connection.

while iq.check_connect() == False:  # detect the websocket is close
    print("try reconnect")
    iq.connect()  # try to connect
    print("reconnect Success")
    time.sleep(1)

# send status updated.
print("\n\n\tConnection Success.\n\n")
print('\nWorking in \"' + mode + ' MODE\"\n')
# check balance and change mode.
iq.change_balance(mode)
balance = float(str(iq.get_balance()))

currency_pair = {
    'EURUSD', 'USDJPY', 'GBPUSD', 'USDCHF', 'EURJPY', 'USDCAD', 'AUDUSD'
}

browser = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    user_agent=
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
)


def check_winrate(action):
    browser.open("https://binary-signal.com/en/chart/" + action)
    list_history = str(
Example #19
0
class MainWindow(QMainWindow, Ui_MainWindow):
	def __init__(self, *args, **kwargs):
		super(MainWindow, self).__init__(*args, **kwargs)
		self.setupUi(self)

		self._generator = None
		self._timerId = None
		sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)

		self.sinais_usados = []

		self.opcaoBinaria = 'live-deal-binary-option-placed' # Binária
		self.filtro = []
		self.lucro = 0
		
		self.pushButton_login.clicked.connect(self.logar)
		self.pushButton_chooseFile.clicked.connect(self.getFiles)
		self.comboBox_chooseMode.activated.connect(self.getComboValue)
		self.realOrTraining = ['Treinamento', 'Conta Real']
		self.comboBox_chooseMode.addItems(self.realOrTraining) 
		self.opcoesListCopy = ['COPIAR ENTRADAS', 'CARREGAR LISTA']
		self.comboBox_listaCopy.addItems(self.opcoesListCopy)  
		self.comboBox_listaCopy.activated.connect(self.listaOuCopy)
		self.countries = ['Mundo','África do Sul', 'Brasil', 'Colômbia' ,'Índia','Tailândia',]
		self.comboBox_chooseCountry.addItems(self.countries)
		self.comboBox_chooseCountry.activated.connect(self.chooseCountry)
		self.check_porcentagem.stateChanged.connect(self.setarPorcentagem)
		self.pushButton_start.clicked.connect(self.start)
		self.pushButton_stop.clicked.connect(self.stop)	
		self.lineEdit_senha.returnPressed.connect(self.logar) 
		self.listaOuCopy()
		self.show()

	def setarPorcentagem(self):
		if self.check_porcentagem.isChecked() == True:
			print('Você selecionou valor em porcentagem.')
		else:
			print('Você selecionou valor unitário.')

	def logar(self):
		self.email=str(self.lineEdit_email.text())
		self.senha=str(self.lineEdit_senha.text())
		self.API = IQ_Option(self.email, self.senha)
		self.API.connect()
		if not self.API.check_connect():
			print('Erro na conexão. Tente novamente.')
			self.label_13.setText("Erro na conexão")
			self.label_13.setStyleSheet("color: #FF0000;")
		else:
			print('Conectado com sucesso!')
			self.label_13.setText("Conectado")
			self.label_13.setStyleSheet("color: #08F26E;")
			self.comboBox_chooseMode.setCurrentIndex(0)
			self.API.change_balance('PRACTICE')
			self.label_banca.setText(str(self.API.get_balance()))

	def listaOuCopy(self):
		if self.comboBox_listaCopy.currentIndex() == 0:
			self.spinBox_ranking.show()
			self.spinBox_ranking1.show()
			self.label_26.show()
			self.label_28.show()
			self.label_29.show()
			self.radioButton_Copy.show()
			self.comboBox_chooseCountry.show()
			self.spinBox_rankingFixo.show()
			self.radioButton_Posicao.show()
			self.spinBox_valorMin.show()
			self.label_30.show()
			self.label_5.hide()
			self.label_8.hide()
			self.pushButton_chooseFile.hide()
		elif self.comboBox_listaCopy.currentIndex() == 1:	
			self.label_5.show()
			self.label_8.show()
			self.pushButton_chooseFile.show()
			self.spinBox_ranking.hide()
			self.spinBox_ranking1.hide()
			self.label_26.hide()
			self.label_28.hide()
			self.label_29.hide()
			self.label_30.hide()
			self.radioButton_Copy.hide()
			self.comboBox_chooseCountry.hide()
			self.spinBox_valorMin.hide()
			self.spinBox_rankingFixo.hide()
			self.radioButton_Posicao.hide()

	def timestampConverter(self, time):  
		hora = datetime.strptime(datetime.utcfromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
		hora = hora.replace(tzinfo=tz.gettz('GMT'))

		return str(hora.astimezone(tz.gettz('America/Sao Paulo')))[:-6]

	def timestampConverterCopy(self, x, y, z):
		timestamp1, ms1 = divmod(x, 1000)
		timestamp2, ms2 = divmod(y, 1000)
		timestamp3, ms3 = divmod(z, 1000)

		entradacodt = datetime.fromtimestamp(timestamp1) + timedelta(milliseconds=ms1)
		expiracaodt = datetime.fromtimestamp(timestamp2) + timedelta(milliseconds=ms2)
		horaatualdt = datetime.fromtimestamp(timestamp3) + timedelta(milliseconds=ms3)

		entradaco = entradacodt.strftime('%Y-%m-%d %H:%M:%S')
		expiracao = expiracaodt.strftime('%Y-%m-%d %H:%M:%S')
		horaatual = horaatualdt.strftime('%Y-%m-%d %H:%M:%S')


		mintime1 = timedelta(milliseconds=x)
		mintime2 = timedelta(milliseconds=y)	
		mintime3 = timedelta(milliseconds=z)
		min1 = mintime1.seconds
		min2 = mintime2.seconds	
		min3 = mintime3.seconds	

		exptime = min2 - min1
		delaytime = min3 - min1                         
		expminutes = (exptime % 3600) // 60   
		if expminutes == 0:
			expminutes = 1                       
	
		return [entradaco, expiracao, horaatual, expminutes, delaytime]	

	def chooseCountry(self):
		if self.comboBox_chooseCountry.currentIndex() == 0:
			print('Você mudou para o Ranking Mundial.')
			self.country = "Worldwide"
		elif self.comboBox_chooseCountry.currentIndex() == 1: 
			print('Você mudou para o Ranking Sul-Africano.')
			self.country = "SA"
		elif self.comboBox_chooseCountry.currentIndex() == 2: 
			print('Você mudou para o Ranking Brasileiro.')
			self.country = "BR"
		elif self.comboBox_chooseCountry.currentIndex() == 3: 
			print('Você mudou para o Ranking Colombiano.')
			self.country = "CO"
		elif self.comboBox_chooseCountry.currentIndex() == 4: 
			print('Você mudou para o Ranking Indiano.')
			self.country = "IN"
		elif self.comboBox_chooseCountry.currentIndex() == 5: 
			print('Você mudou para o Ranking Tailândes.')
			self.country = "TH"

	def filtroRanking(self, country, numeroInicial, numeroFinal):
		self.filtro.clear()
		while True:		
			try:
				ranking = self.API.get_leader_board(self.country, self.numeroInicial, self.numeroFinal, 0)

				for n in ranking['result']['positional']:
					id = ranking['result']['positional'][n]['user_id']
					self.filtro.append(id)
			except:
				pass

			time.sleep(180)
			 #Atualiza Ranking a cada 3 minutos.

	def ajustesEntradaBinaria(self, ti):
		global lastplayer
		trades = self.API.get_live_deal(ti)
		for trade in list(trades):
			if self.check_porcentagem.isChecked() == True:
				self.valor_entrada = (int(self.spinBox_gerenciamento.value()))*(float(self.spinBox_valueEntry.value()/100))
			else: 
				self.valor_entrada = float(self.spinBox_valueEntry.value())

			self.valorMin = int(self.spinBox_valorMin.value()) 
			self.mGale = int(self.spinBox_martingale.value())
			entradacopy = trade['created_at']	
			expiracao = trade['expiration']
			horalocal = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
			timecopy = self.timestampConverterCopy(entradacopy, expiracao, horalocal)

			if lastplayer != trade['user_id'] and trade['amount_enrolled'] >= int(self.valorMin) and int(timecopy[3]) < 20 and int(timecopy[4]) < 3:
				if trade['user_id'] in self.filtro:
					lastplayer = trade['user_id']
					ativo = list(ACTIVES.keys())[list(ACTIVES.values()).index(trade['active_id'])]

					print("\nNOME: "+str(trade['name'])+" | PAÍS: "+str(trade['flag'])+" | $ "+str(trade['amount_enrolled'])+"\n"+ trade['direction'].upper() + " | " +str(ativo)+" | "+str(timecopy[0])) 
					print("SUA ENTRADA: $ "+str(round(self.valor_entrada, 2))+" | DELAY: "+str(timecopy[4] + 1)+"s")

					bcall = Thread(target=self.entrada, args=(self.valor_entrada, str(ativo), trade['direction'], int(timecopy[3]), horalocal, self.mGale))
					bcall.start()

			trades.clear()
					

	def comecarCopy(self):
		self.API.subscribe_live_deal(self.opcaoBinaria, 10)

		if self.radioButton_Copy.isChecked() == True: 
			self.numeroInicial=int(self.spinBox_ranking.value())
			self.numeroFinal=int(self.spinBox_ranking1.value())
		else: 
			self.numeroInicial=int(self.spinBox_ranking.value())
			self.numeroFinal=int(self.spinBox_ranking.value())

		if self.numeroInicial == self.numeroFinal:
			print("Carregando entradas do Top " + str(self.numeroInicial))
		elif self.numeroInicial != self.numeroFinal:
			print("Carregando entradas do Top "+ str(self.numeroInicial) + " ao " + str(self.numeroFinal) +".")

		catalogo = Thread(target=self.filtroRanking, args=(self.country, self.numeroInicial, self.numeroFinal))
		catalogo.daemon = True
		catalogo.start()

		while True:
			self.ajustesEntradaBinaria(self.opcaoBinaria)
			yield 
			
		self.API.unscribe_live_deal(self.opcaoBinaria)

	def getFiles(self):
		self.filename = QFileDialog.getOpenFileName(None, 'Select a file', '', '*.txt')
		self.path = self.filename[0]    

		with open(self.path, "r") as f:
			self.text = f.read()
			self.textEdit_output.setText(self.text)

	def carregarSinais(self):
		with open(self.path, "r") as f:
			self.text = f.read()
			self.textEdit_output.setText(self.text)
			f.close()
			self.text = self.text.split('\n')
			for index, a in enumerate(self.text):
				if a == '':
					del self.text[index]
		return self.text

	def normalOutputWritten(self, textw):
		cursor = self.textEdit_terminal.textCursor()
		cursor.movePosition(QTextCursor.End)
		cursor.insertText(textw)
		self.textEdit_terminal.setTextCursor(cursor)
		self.textEdit_terminal.ensureCursorVisible()
		
	def stopWL(self, lucro, gain,loss):
		if self.lucro <= float('-' + str(abs(loss))):
			print('Stop Loss batido!')
			self.stop()
		if self.lucro >= float(abs(gain)):
			print('Stop Win batido!')
			self.stop()

	def stopWLM(self, lucro, gain,loss):
		if self.lucro <= float('-' + str(abs(loss))):
			sys.exit()
		if self.lucro >= float(abs(gain)):
			sys.exit()

	def meucheckwin(self, id_number): 
		while True:
			stat, lista = self.API.get_position_history_v2('turbo-option', 15, 0, 0, 0) #15 é a quantidade de orders passadas quiser puxar. Pode por quantas quiser.
			xindex = next((index for (index, d) in enumerate(lista['positions']) if d['raw_event']['option_id'] == id_number), -1)
			if xindex >=0:
				x = list(lista['positions'])
				lucro = x[xindex]['close_profit']
				invest = x[xindex]['invest']
				resultado = lucro - invest
				return resultado
				break

	def entrada(self, valor, par_moedas, acao_entrada, expiracao, hora_operacao, gale):
		status, id_order = self.API.buy(valor, par_moedas, acao_entrada, expiracao)
		print(id_order)
		if status:
			resultado = self.meucheckwin(id_order)
			self.lucro += round(resultado, 2)
			if self.check_porcentagem.isChecked() == True: 
				self.stopWin = (float(self.spinBox_gerenciamento.value()))*(float(int(self.spinBox_stopWin.value())/100))
				self.stopLoss = (float(self.spinBox_gerenciamento.value()))*(float(int(self.spinBox_stopLoss.value())/100))
			else: 
				self.stopWin = float(self.spinBox_stopWin.value())
				self.stopLoss = float(self.spinBox_stopLoss.value())


			if resultado > 0 :
				print('\n✅ WIN | ' + 'LUCRO: $ ' + str(round(resultado, 2)) + ' | ' + str(acao_entrada.upper()) + ' ' + str(par_moedas))
			elif resultado == 0:
				print('\nEMPATE | ' + 'LUCRO: $ ' + str(round(resultado, 2)) + ' | ' + str(acao_entrada.upper()) + ' ' + str(par_moedas))
			elif resultado < 0:
				print('\n❌ LOSS | ' + 'LUCRO: $ ' + str(round(resultado, 2)) + ' | ' + str(acao_entrada.upper()) + ' ' + str(par_moedas))

			self.stopWL(self.lucro, self.stopWin, self.stopLoss)
			if resultado < 0 and gale > 0:
				valor_com_martingale = (valor * 2.2)
				self.stopWLM(self.lucro, self.stopWin, self.stopLoss)
				print('\n🔁 MARTINGALE ' + str(gale) + ' | VALOR: $ ' + str(round(valor_com_martingale, 2)) + ' | ' + acao_entrada.upper() + ' ' + par_moedas)
				gale = gale - 1
				Thread(target=self.entrada, args=(valor_com_martingale, par_moedas, acao_entrada, expiracao, self.timestampConverter(self.API.get_server_timestamp()), gale,)).start()
				return True
			return True
		else:
			print('Não foi possivel realizar a sua entrada.')
			return False

	def martinGale(self, tipo, valor):
		if tipo == 'auto':
			return valor * 2.2

	def loopGenerator(self):
		while True:
			self.agora = self.timestampConverter(self.API.get_server_timestamp())
			for sinal in self.text:
				dados = sinal.split(',')
				if dados[0] == self.agora and sinal not in self.sinais_usados:
					self.sinais_usados.append(sinal)
					valor_entrada = (float(self.spinBox_gerenciamento.value()))*(float(self.spinBox_valueEntry.value()/100))
					par = dados[1]
					acao = dados[2].lower()
					expiracao = int(dados[3])
					gale = int(self.spinBox_martingale.value())
					print('\n' + acao.upper() + ' | ' + par + ' | ' + self.agora + '\nSUA ENTRADA: $ ' + str(valor_entrada))
					Thread(target=self.entrada, args=(valor_entrada, par, acao, expiracao, dados[0], gale,)).start()
				yield

	def start(self):
		if self.comboBox_listaCopy.currentIndex() == 0:
			print('Aplicação inicializada!')
			self.stop()  # Stop any existing timer
			self._generator = self.comecarCopy()  # Start the loop
			self._timerId = self.startTimer(0)
		else:
			self.text = self.carregarSinais()
			print('Aplicação inicializada!')
			print('Sinais prontos! Aguardando hora de entrada.')
			self.stop()  # Stop any existing timer
			self._generator = self.loopGenerator()  # Start the loop
			self._timerId = self.startTimer(0)

	def stop(self):
		if self._timerId is not None:
			print('Aplicação parada!')
			self.killTimer(self._timerId)
			self.label_banca.setText(str(self.API.get_balance()))
		self._generator = None
		self._timerId = None

	def timerEvent(self, event):
		# This is called every time the GUI is idle.
		if self._generator is None:
			return
		try:
			next(self._generator)  # Run the next iteration
		except StopIteration:
			self.stop()

	def getComboValue(self):
		if self.comboBox_chooseMode.currentIndex():
			print('Você mudou para a Conta Real.')
			self.API.change_balance('REAL')
			self.label_banca.setText(str(self.API.get_balance()))
		elif self.comboBox_chooseMode.currentIndexChanged: 
			print('Você mudou para a Conta de Treinamento.')
			self.API.change_balance('PRACTICE')
			self.label_banca.setText(str(self.API.get_balance()))
Example #20
0
PW = input('Password: '******'Run times: ')
Max_bet_amount_limit_set = input('Max bet limits: ')

print('login..')

I_want_money = IQ_Option(ID + "@gmail.com", PW)
#connect to iqoption
I_want_money.connect()
start_time_results = datetime.fromtimestamp(I_want_money.get_server_timestamp() + 3600 * 8)


I_want_money.change_balance('REAL')

start_balance_results = I_want_money.get_balance()
print(start_balance_results)
# get_all_open_time for choice array
ALL_Asset = dict
d = dict





def run(choice_market):
    I_want_money = IQ_Option(ID + "@gmail.com", PW)
    I_want_money.connect()
    # I_want_money.change_balance('PRACTICE')
    I_want_money.change_balance('REAL')
    start_balance = I_want_money.get_balance()
Example #21
0
    time.sleep(1)


def convert_timestamp(x):

    hora = datetime.strptime(
        datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S'),
        '%Y-%m-%d %H:%M:%S')
    hora = hora.replace(tzinfo=tz.gettz('GMT'))
    return hora


def perfil():
    perfil = json.loads(json.dumps(API.get_profile_ansyc()))
    return perfil


balance = API.get_balance()
print('O saldo da conta está em ', balance, '\n')
x = perfil()
print(x['name'])
print(x['nickname'])
print('A conta foi criada em ', convert_timestamp(x['created']))

modo_investimento = 'EURUSD'
velas = API.get_candles(modo_investimento, 5, 60, time.time())

for i in velas:
    API.connect()
    print(i, '\n')
Example #22
0
    awaiting_bounce = False
    for x in range(0, len(low)):
        if abs(low[x] - minima) < move_allowance and not awaiting_bounce:
            touchdown = touchdown + 1
            awaiting_bounce = True
        elif abs(low[x] - minima) > bounce_distance:
            awaiting_bounce = False
    if touchdown >= min_touches:
        sup = minima
    return sup, res
 
 
 
 
 
current_value1=API.get_balance()
current_value2=0
def take_lov():
  while True:
      instrument1 = ["AMAZON","APPLE","BAIDU","CISCO","FACEBOOK","GOOGLE","INTEL","MSFT","YAHOO","AIG","CITI","COKE","GE","GM","GS","JPM","MCDON","MORSTAN","TWITTER","FERRARI","TESLA","USDNOK","MMM:US"]
      y={}
      y1 = json.dumps(y)
      # parsing JSON string:
      z = json.loads(y1)
      instrument=[]
      for i in range(len(instrument1)):
          instruments = instrument1.copy()
          ALL_Asset=API.get_all_open_time()
          print(ALL_Asset["cfd"][instruments[i]]["open"])
          if ALL_Asset["cfd"][instruments[i]]["open"]==True:
            df = data(60, instruments[i],700)
Example #23
0
                            MODE = 'REAL'
                            tipo_conta_saida = 'Conta real'
                        else:
                            MODE = 'PRACTICE'
                            tipo_conta_saida = 'Conta de treinamento'
                    break

            if licenca == False:
                print('\nLICENCA INVALIDA PARA O EMAIL INFORMADO')
                print('\nO SISTEMA FUNCIONARA APENAS EM MODO DE TREINAMENTO')
                MODE = 'PRACTICE'
                tipo_conta_saida = 'Conta de treinamento'

            API.change_balance(MODE)

            saldo = API.get_balance()

            print('\nBANCA INICIAL: ', dados_conta['currency_char'], saldo)
            data_atual = date.today()
            data_em_texto = data_atual.strftime('%d%m%Y')
            arquivoLOG = open('log de operacoes/'+data_em_texto+'.txt', 'w')
            arquivoLOG.close()
            arquivoLOGop = open('log/op.txt', 'w')
            arquivoLOGop.close()

            if porcentagem == True:
                stop_win = (take_profit * saldo) / 100
                stop_loss = ((take_loss * saldo) / 100) * -1

            else:
                stop_win = take_profit
from iqoptionapi.stable_api import IQ_Option
import logging
import time
# logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(message)s')
Iq = IQ_Option("*****@*****.**", "aswdkl;123")
# Iq = IQ_Option(content['email'], content['password'])
Iq.connect()
Money = []
ACTIVES = []
ACTION = []
expirations_mode = []
res = Iq.get_balance()
print(res)
print(Iq.check_connect())
Money.append(1)
ACTIVES.append("EURUSD")
ACTION.append("call")  #put
expirations_mode.append(1)

Money.append(1)
ACTIVES.append("EURAUD")
ACTION.append("call")  #put
expirations_mode.append(1)

print("buy multi")
id_list = Iq.buy_multi(Money, ACTIVES, ACTION, expirations_mode)

print("check win only one id (id_list[0])")
print(Iq.check_win_v2(id_list[0], 2))
Example #25
0
from iqoptionapi.stable_api import IQ_Option
import logging
import time

I = IQ_Option("*****@*****.**", "aswdkl;123")
check, reason = I.connect()
print(check, reason)
res = I.get_balance()
print(res)
# print(res["id"])
Example #26
0
    return sup, res



def binary(direcao, par):
    try:
        id = API.buy(1, par, direcao,2)
    except:
        None
    return id

res1=['start']
money1=[80,90,100]
money2=[80,100,225]
current_money=80
current_money1=API.get_balance()

def multiply(res1,money1,money2,current_money):
    if res1[len(res1) - 1] == 'start':
        return current_money
    elif res1[len(res1) - 1] == 'loose':
        i = len(res1) - 1
        count = 0
        while True:
            if res1[i] == 'win' or res1[i] == 'start':
                break
            elif res1[i] == 'loose':
                count = count + 1
            i = i - 1
        if count >= len(money2):
            res1[i] == 'loose'
Example #27
0
#Fazendo a compra

investimento = 4.50
gale = 4

pares = [
    "EURUSD", "GBPUSD", "EURGBP", 'USDJPY', 'EURJPY', 'CADJPY', 'GBPJPY',
    'AUDJPY'
]
#pares = ["EURUSD", "EURGBP",'EURJPY','USDCHF','GBPUSD']
numberRandom = randint(0, 7)
valor = investimento
entrada = 'put'
tempo = 1

banca = API.get_balance()
metaPorcentagem = 2
meta = banca * (100 / metaPorcentagem)

quantidadeentradas = 0
acerto = 0
erroCont = 0
erro = 0
doji = 0

par = pares[numberRandom]

acertividade = 0

#compra_status, id_compra = API.buy_digital_spot(pares, valor, entrada, tempo )
Example #28
0
class IQ:
    def __init__(self):
        self.api = IQ_Option(os.environ["IQU"], os.environ["IQP"])
        self.api.connect()
        self.api.change_balance(ARG_BALANCE)
        self.currency = ARG_CURRENCY

        while True:
            if self.api.check_connect() == False:
                print('Erro ao conectar')
                self.api.connect
            else:
                print('Conectado com Sucesso')
                break
            time.sleep(3)

    def getCurrency(self):
        return self.currency

    def getBalance(self):
        return self.api.get_balance()

    def getEnterValue(self):
        banca = self.getBalance()
        bancaFloor = math.floor(banca / 40)
        return bancaFloor if int(banca) > 40 else 2.0
        # Limited to $USD 2

    def getServerDatetime(self):
        serverTime = self.api.get_server_timestamp()
        hora = datetime.strptime(
            datetime.utcfromtimestamp(serverTime).strftime(
                '%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        return hora.replace(tzinfo=tz.gettz('GMT'))

    def getCandles(self, rangeTime=60, quant=10):
        return self.api.get_candles(self.currency, rangeTime, quant,
                                    self.api.get_server_timestamp())

    def buyDigital(self, direction):
        return self.api.buy_digital_spot(self.currency, self.getEnterValue(),
                                         direction, ARG_DURATION)

    def checkResult(self, id):
        return self.api.check_win_digital_v2(id)

    def shouldEntry(self):
        serverTime = self.getServerDatetime()
        # minutes = float(serverTime.strftime('%M.%S')[1:])
        # return True if (minutes >= 4.58 and minutes <= 5) or minutes >= 9.58 else False
        seconds = int(serverTime.strftime('%S'))

        if seconds < 20:
            time.sleep(20)
        elif seconds < 30:
            time.sleep(10)

        goTrade = True if (seconds >= 48
                           and seconds <= 50) or seconds >= 58 else False
        if goTrade == False:
            time.sleep(1)

        return goTrade
Example #29
0
        email
        city
        nickname
        currency
        currency_char 
        address
        created
        postal_index
        gender
        birthdate
        balance
    '''


x = perfil()
banca = API.get_balance()

######################### IMPRESSAO ########################

print(x['name'])
print(banca)


def timestamp_converter(x):  # Função para converter timestamp
    hora = datetime.strptime(
        datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S'),
        '%Y-%m-%d %H:%M:%S')
    hora = hora.replace(tzinfo=tz.gettz('GMT'))

    return str(hora.astimezone(tz.gettz('America/Sao Paulo')))[:-6]