Пример #1
0
def D(change_acc, viewTrend, qtdCandleTrend, trendEmaSma, priorid, operation):
    E = '0'
    if int(date.today().day) == int(operation.day):
        if VerifConnection():
            if change_acc:
                A.instance().connection.change_balance(A.instance().acc_type)
            Pdig, Pbin = buscaPayout(operation.pair, operation.expirationMode)
            if int(Pdig + Pbin) > 0:
                B.info('{} | {}M | Payout Digital: {} | Binary: {}',
                       operation.pair, operation.expirationMode, Pdig, Pbin)
            prioriDigital = 1
            if operation.expirationMode > 15:
                prioriDigital = 0
            elif int(Pbin) > int(Pdig) and priorid == 0:
                prioriDigital = 0
            elif priorid == 1:
                prioriDigital = 1
            elif priorid == 2:
                prioriDigital = 0
            if prioriDigital:
                operation.payout = Pdig
            else:
                operation.payout = Pbin
            TipoAtivo = 'Digital'
            AtAberto = Idioma.traducao('Fechado')
            Tp, Ab = ativoAberto(operation.pair, prioriDigital)
            if Ab:
                operation.typepair = Tp
                AtAberto = Idioma.traducao('Aberto')
            if Tp == 'B':
                TipoAtivo = 'Binarias'
            if prioriDigital:
                if Tp == 'B':
                    operation.payout = Pbin
            elif Tp == 'D':
                operation.payout = Pdig
            B.info('{} | {} | {}', operation.pair, TipoAtivo, AtAberto)
            if not Ab or viewTrend and trendEmaSma:
                operation.trend, sq = getIndicadores(operation.pair,
                                                     operation.expirationMode)
                if operation.trend != '':
                    B.info('{} | Tendência: {}', operation.pair,
                           operation.trend)
                    B.info(sq)
                else:
                    B.info('{} | Tendência: {}', operation.pair,
                           'Sem resposta da IQ')
            else:
                operation.trend, sq = tendenciaCandles(
                    operation.pair, operation.expirationMode, qtdCandleTrend)
                if operation.trend != '':
                    B.info('{} | Tendência: {} | {}', operation.pair,
                           operation.trend, sq)
        else:
            msg = '{0} | {1}M | {2}'.format(
                operation.pair, operation.expirationMode,
                Idioma.traducao(
                    'Problema na conexão, verifique sua internet.'))
            B.error(msg)
            print(msg)
Пример #2
0
def getCandles(candle_ativo: str, candle_duracao: int, candle_ticks: int):
    data = []
    if candle_ticks > 1000:
        resultdiv = decimal.getcontext().divmod(candle_ticks, 1000)
        qtdefor = int(resultdiv[0])
        fracao = str(resultdiv[1])
        qtdesobrou = int(fracao)
        ANS = []
        errocnt = 0
        candle_ticks = 1000
        end_from_time = time.time()
        if qtdefor > 0:
            for i in range(qtdefor):
                data = APIConnection.instance().connection.get_candles(
                    candle_ativo, candle_duracao * 60, candle_ticks,
                    end_from_time)
                ANS = data + ANS
                end_from_time = int(data[0]['from']) - 1

        if qtdesobrou > 0:
            candle_ticks = qtdesobrou
            data = APIConnection.instance().connection.get_candles(
                candle_ativo, candle_duracao * 60, candle_ticks, end_from_time)
            ANS = ANS + data
        data = ANS
    else:
        data = APIConnection.instance().connection.get_candles(
            candle_ativo, candle_duracao * 60, candle_ticks, time.time())
    return data
Пример #3
0
def D(idaction, typepair, dhend):
    status = False
    win = 0
    try:
        dhend = dhend + timedelta(seconds=15)
        if typepair == 'D':
            while datetime.now() <= dhend:
                status, win = APIConnection.instance(
                ).connection.check_win_digital_v2(idaction)
                if status:
                    break
                else:
                    time.sleep(1)

        else:
            result = APIConnection.instance().connection.check_binary_order(
                idaction)
            status = result['result']
            try:
                win = round(
                    float(result['profit_amount']) - float(result['amount']),
                    2)
            except:
                win = 0

    except Exception as e:
        try:
            pass
        finally:
            e = None
            del e

    return (status, win)
Пример #4
0
    def try_connection(self):
        while roboCtrl.instance().robo.iniciado:
            if self.first_check == 0:
                if roboCtrl.instance().dianoticias != datetime.now().date():
                    getNoticias()
                else:
                    try:
                        if not APIConnection.instance(
                        ).connection.check_connect():
                            log.debug(
                                Idioma.traducao('Recuperando conexão...'))
                            print(Idioma.traducao('Recuperando conexão...'))
                            APIConnection.instance().connection.connect()
                        server_time = APIConnection.instance(
                        ).connection.get_server_timestamp()
                        local_time = time.time()
                        diff = local_time - server_time
                        self.first_check = diff
                        log.debug(
                            Idioma.traducao('Diferenca de horario:') + ' {}s',
                            round(diff, 3))
                        roboCtrl.instance().view.janela['-status-'].update(
                            Idioma.traducao('Diferenca de horario:') +
                            ' {0}s'.format(round(diff, 3)))
                        roboCtrl.instance().view.janela.Refresh()
                    except Exception as e:
                        try:
                            log.error(e)
                        finally:
                            e = None
                            del e

                    time.sleep(0.5)
Пример #5
0
def createapiconnection(user: str, passw: str, tp_conta: str):
    apiconn = apiconnect(user, passw)
    if apiconn:
        apiconn.change_balance(tp_conta)
        APIConnection.instance().connection = apiconn
        APIConnection.instance().acc_type = tp_conta
        balance = apiconn.get_balance()
        log.warning(
            Idioma.traducao('Conta conectada:') + ' {} | ' +
            Idioma.traducao('Saldo Atual $') + ' {}', apiconn.email, balance)
        print(Idioma.traducao('Conta conectada:'), apiconn.email)
        Balance.instance().balance = balance
        Balance.instance().actual_balance = balance
        Balance.instance().moeda = apiconn.get_currency()
Пример #6
0
def VerifConnection():
    error_password = '******'
    conOK = False
    verAtivos = False
    try:
        log.debug(Idioma.traducao('Verificando conexão...'))
        conOK = APIConnection.instance().connection.check_connect()
    except Exception as e:
        try:
            log.error('Erro de conexão com a IQ:')
            log.error(e)
        finally:
            e = None
            del e

    try:
        if not conOK:
            verAtivos = True
            log.debug(Idioma.traducao('Recuperando conexão...'))
            print(Idioma.traducao('Recuperando conexão...'))
            check, reason = APIConnection.instance().connection.connect()
            if check:
                log.warning(Idioma.traducao('Conexão recuperada.'))
                print(Idioma.traducao('Conexão recuperada.'))
                conOK = True
            elif reason == '[Errno -2] Name or service not known':
                log.error(
                    Idioma.traducao(
                        'Problema na conexão, verifique sua internet.'))
                print(
                    Idioma.traducao(
                        'Problema na conexão, verifique sua internet.'))
            elif reason == error_password:
                log.error(Idioma.traducao('Login/Senha inválido.'))
                print(Idioma.traducao('Login/Senha inválido.'))
        else:
            conOK = True
    except Exception as e:
        try:
            log.error(e)
        finally:
            e = None
            del e

    if conOK:
        if roboCtrl.instance().dianoticias != datetime.now().date():
            getNoticias()
        if verAtivos:
            roboCtrl.instance().robo.pesqAtviso.start_ativos()
    return conOK
Пример #7
0
def ativoAberto(ativo, prioriDigital):
    aberto = False
    tipo = 'D'
    if prioriDigital:
        tipos = ['digital', 'turbo', 'binary']
    else:
        tipos = ['turbo', 'binary', 'digital']
    par = roboCtrl.instance().robo.ativosabertos
    if par == []:
        par = A.instance().connection.get_all_open_time()
        roboCtrl.instance().robo.ativosabertos = par
    for tpnome in tipos:
        if not aberto:
            for paridade in par[tpnome]:
                if paridade == ativo:
                    if par[tpnome][paridade]['open'] == True:
                        aberto = True
                        break

        if aberto:
            if tpnome == 'digital':
                tipo = 'D'
            else:
                tipo = 'B'
            break

    return (tipo, aberto)
Пример #8
0
def C(operation, valuecurrenc):
    O = operation
    status = False
    id = 0
    taxa = 0
    if O.typepair == 'D':
        status, id = APIConnection.instance().connection.buy_digital_spot(
            O.pair, float(valuecurrenc),
            str(O.direction).lower(), int(O.expirationMode))
        if status:
            try:
                res = APIConnection.instance().connection.get_digital_position(
                    id)
                orders = res['msg']['position']['orders']
                for order in orders:
                    if order['id'] == id:
                        taxa = order['instrument_strike']
                        break

            except Exception as e:
                try:
                    pass
                finally:
                    e = None
                    del e

    else:
        try:
            status, id, taxa = APIConnection.instance().connection.buy(
                float(valuecurrenc), O.pair,
                str(O.direction).lower(), int(O.expirationMode))
        except Exception as e:
            try:
                pass
            finally:
                e = None
                del e

    if not isinstance(taxa, float):
        taxa = 0
    return (status, id, float(taxa))
Пример #9
0
def getIndicadores_old(ativo: str, duracao: int):
    oscila_put = 0
    oscila_neu = 0
    oscila_call = 0
    medias_put = 0
    medias_neu = 0
    medias_call = 0
    pivots_put = 0
    pivots_neu = 0
    pivots_call = 0
    try:
        data = A.instance().connection.get_technical_indicators(ativo)
        for item in data:
            if int(item['candle_size']) == duracao * 60:
                if str(item['group']).lower() == 'OSCILLATORS'.lower():
                    if str(item['name']).lower() == 'Relative Strength Index (14)'.lower() or str(item['name']).lower() == 'Stochastic RSI Fast (3, 3, 14, 14)'.lower():
                        if str(item['action']).lower() == 'sell':
                            oscila_put += 1
                        if str(item['action']).lower() == 'buy':
                            oscila_call += 1
                        if str(item['action']).lower() == 'hold':
                            oscila_neu += 1
                if not str(item['group']).lower() == 'MOVING AVERAGES'.lower() or str(item['name']).lower() == 'Exponential Moving Average (5)'.lower() or str(item['name']).lower() == 'Simple Moving Average (20)'.lower():
                    if str(item['action']).lower() == 'sell':
                        medias_put += 1
                    if str(item['action']).lower() == 'buy':
                        medias_call += 1
                    if str(item['action']).lower() == 'hold':
                        medias_neu += 1
                if str(item['group']).lower() == 'PIVOTS'.lower():
                    if str(item['action']).lower() == 'sell':
                        pivots_put += 1
                    elif str(item['action']).lower() == 'buy':
                        pivots_call += 1
                    if str(item['action']).lower() == 'hold':
                        pivots_neu += 1

    except:
        pass

    descricao = 'Médias: CALL={0} PUT={1} NEUTRO={2}'.format(medias_call, medias_put, medias_neu)
    descricao = descricao + '\nOsciladores: CALL={0} PUT={1} NEUTRO={2}'.format(oscila_call, oscila_put, oscila_neu)
    if medias_call + oscila_call > medias_put + medias_neu + oscila_put + oscila_neu:
        tendencia = 'call'
    elif medias_put + oscila_put > medias_call + medias_neu + oscila_call + oscila_neu:
        tendencia = 'put'
    return (tendencia, descricao)
Пример #10
0
def tendenciaCandles(ativo, expiracao, ticks: int):
    try:
        if ticks <= 0:
            ticks = 2
        doji = 0
        call = 0
        put = 0
        tot = 0
        dire = ''
        seq = ''
        agora = datetime.now() - timedelta(minutes=expiracao)
        hora = datetime.timestamp(agora)
        candles = A.instance().connection.get_candles(ativo, 60 * expiracao, int(ticks), hora)
        for candle in candles:
            tot += 1
            if candle['close'] > candle['open']:
                call += 1
                seq = seq + 'G'
            else:
                if candle['close'] < candle['open']:
                    put += 1
                    seq = seq + 'R'
                else:
                    doji += 1
                    seq = seq + 'C'

        pcall = 0
        pput = 0
        if call > 0:
            pcall = int(round(call / tot) * 100)
        if put > 0:
            pput = int(round(put / tot) * 100)
        if pcall >= 55:
            dire = 'call'
        elif pput >= 55:
            dire = 'put'
    except Exception as inst:
        try:
            B.error(inst)
        finally:
            inst = None
            del inst

    return (
     dire, seq)
Пример #11
0
def buscaPayout(ativo, duracao):
    duracao = int(duracao)
    tenta = 0
    payoutDig = 0
    payoutBin = 0
    try:
        A.instance().connection.subscribe_strike_list(ativo, duracao)
        while 1:
            data = A.instance().connection.get_digital_current_profit(
                ativo, duracao)
            if data:
                payoutDig = int(data)
                break
            else:
                time.sleep(1)
                tenta += 1
            if tenta >= 10:
                break

        A.instance().connection.unsubscribe_strike_list(ativo, duracao)
    except Exception as inst:
        try:
            B.error(inst)
        finally:
            inst = None
            del inst

    try:
        data = A.instance().connection.get_all_profit()
        payout_tur = int(data[ativo]['turbo'] * 100)
        payout_bin = int(data[ativo]['binary'] * 100)
        if duracao >= 15:
            if payout_bin > 0:
                payoutBin = payout_bin
            else:
                payoutBin = payout_tur
        elif payout_tur > 0:
            payoutBin = payout_tur
        else:
            payoutBin = payout_bin
    except Exception as inst:
        try:
            pass
        finally:
            inst = None
            del inst

    return (payoutDig, payoutBin)
Пример #12
0
def getIndicadores(ativo: str, duracao: int):
    oscila_put = 0
    oscila_neu = 0
    oscila_call = 0
    medias_put = 0
    medias_neu = 0
    medias_call = 0
    pivots_put = 0
    pivots_neu = 0
    pivots_call = 0
    descr_ema = ''
    descr_sma = ''
    tendencia = ''
    descricao = ''
    try:
        data = A.instance().connection.get_technical_indicators(ativo)
        for item in data:
            if int(item['candle_size']) == duracao * 60:
                if not str(item['group']).lower() == 'OSCILLATORS'.lower() or str(item['name']).lower() == 'Relative Strength Index (14)'.lower() or str(item['name']).lower() == 'Stochastic RSI Fast (3, 3, 14, 14)'.lower():
                    if str(item['action']).lower() == 'sell':
                        oscila_put += 1
                    if str(item['action']).lower() == 'buy':
                        oscila_call += 1
                    if str(item['action']).lower() == 'hold':
                        oscila_neu += 1
                if str(item['group']).lower() == 'MOVING AVERAGES'.lower():
                    if str(item['name']).lower() == 'Exponential Moving Average (5)'.lower():
                        if str(item['action']).lower() == 'sell':
                            descr_ema = 'EMA5: VENDER'
                            medias_put += 1
                        if str(item['action']).lower() == 'buy':
                            descr_ema = 'EMA5: COMPRAR'
                            medias_call += 1
                        if str(item['action']).lower() == 'hold':
                            descr_ema = 'EMA5: NEUTRO'
                            medias_neu += 1
                    if str(item['name']).lower() == 'Simple Moving Average (20)'.lower():
                        if str(item['action']).lower() == 'sell':
                            descr_sma = 'SMA20: VENDER'
                            medias_put += 1
                        if str(item['action']).lower() == 'buy':
                            descr_sma = 'SMA20: COMPRAR'
                            medias_call += 1
                        if str(item['action']).lower() == 'hold':
                            descr_sma = 'SMA20: NEUTRO'
                            medias_neu += 1
                if str(item['group']).lower() == 'PIVOTS'.lower():
                    if str(item['action']).lower() == 'sell':
                        pivots_put += 1
                    elif str(item['action']).lower() == 'buy':
                        pivots_call += 1
                    if str(item['action']).lower() == 'hold':
                        pivots_neu += 1

        descricao = descr_ema + ' | ' + descr_sma
        if medias_call > medias_put:
            tendencia = 'call'
        elif medias_put > medias_call:
            tendencia = 'put'
    except:
        pass

    return (
     tendencia, descricao)
Пример #13
0
 def Conectar(self):
     T = str(M.b64encode(self.email.encode()))
     self.arqInit = str(R.logs_path) + '/' + T + '_init.conf'
     if os.path.exists(self.arqInit):
         os.remove(self.arqInit)
     if self.contareal:
         self.tipoconta = 'REAL'
     else:
         self.tipoconta = 'PRACTICE'
     if self.ent_tipo == 'P':
         self.ent_valor1 = round(self.valorinicial * self.ent_valor1 / 100,
                                 2)
         self.ent_gale1 = round(self.valorinicial * self.ent_gale1 / 100, 2)
         self.ent_gale2 = round(self.valorinicial * self.ent_gale2 / 100, 2)
     if self.usarsoros:
         self.ent_valor1 = round(self.valorinicial * self.percent / 100, 2)
         self.ent_gale1 = 0
         self.ent_gale2 = 0
         if self.qtdgales > 0:
             self.ent_gale1 = 2
         if self.qtdgales > 1:
             self.ent_gale2 = 2
     else:
         if self.qtdgales < 1:
             self.ent_gale1 = 0
         if self.qtdgales < 2:
             self.ent_gale2 = 0
     if self.loadLista() == 0:
         A.info(
             Idioma.traducao('Lista vazia ou com dia/horário expirados.'))
     A.info(Idioma.traducao('Aguarde, conectando a IQ...'))
     print(Idioma.traducao('Aguarde, conectando a IQ...'))
     self.View.janela.Refresh()
     N.createapiconnection(self.email, self.senha, self.tipoconta)
     conect = API.instance().connection
     if conect:
         if self.VerificarLicenca():
             C.instance().actual_balance = 0
             if self.tipostop == 'P':
                 X = self.stopgain / 100
                 Z = self.stoploss / 100
                 C.instance().win_limit = self.valorinicial * X
                 C.instance().stop_limit = self.valorinicial * Z * -1
             else:
                 C.instance().win_limit = self.stopgain
                 C.instance().stop_limit = self.stoploss * -1
             A.info('Versão: ' + self.versaoapp)
             A.success(
                 Idioma.traducao('Tipo de conta:') + ' {}', self.tipoconta)
             A.info(Idioma.traducao('Parâmetros iniciais:'))
             A.success(
                 Idioma.traducao('Valor inicial: $') + '{}',
                 round(self.valorinicial, 2))
             A.success(
                 Idioma.traducao('Quantidade de gales:') + ' {}',
                 self.qtdgales)
             A.success(
                 Idioma.traducao('Payout mínimo:') + ' {}', self.payoutmin)
             if self.prestop:
                 A.success(Idioma.traducao('Pré-Stop Loss: Ligado'))
             if self.esperarIQ:
                 A.success(Idioma.traducao('Resultado Resp. IQ'))
             else:
                 A.success(Idioma.traducao('Resultado por Taxas'))
             A.success('Delay: {}', self.delay)
             if self.priorid == 0:
                 A.success(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Maior Payout'))
             elif self.priorid == 1:
                 A.success(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Digital'))
             elif self.priorid == 2:
                 A.success(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Binárias'))
             if self.naonoticia:
                 A.success(Idioma.traducao('Não operar em notícia'))
             if self.tendusar:
                 if self.tendemasma:
                     A.success(
                         Idioma.traducao('Não Operar Contra') + ': ' +
                         Idioma.traducao('Usar EMA5 + SMA20'))
                 else:
                     A.success(
                         Idioma.traducao('Não Operar Contra') + ': ' +
                         Idioma.traducao('Quant. Velas') + ': ' +
                         str(self.tendvelas))
             if not self.usarsoros:
                 A.info(Idioma.traducao('Entradas fixas:'))
                 A.success(
                     Idioma.traducao('Entrada: $') + '{}',
                     round(self.ent_valor1, 2))
                 if self.ent_gale1 > 0:
                     A.success(
                         Idioma.traducao('Gale 1: $') + '{}',
                         round(self.ent_gale1, 2))
                 if self.ent_gale2 > 0:
                     A.success(
                         Idioma.traducao('Gale 2: $') + '{}',
                         round(self.ent_gale2, 2))
             else:
                 A.info('Soros:')
                 if self.modelo == 'A':
                     A.success(Idioma.traducao('Modelo: Agressivo'))
                 elif self.modelo == 'M':
                     A.success(Idioma.traducao('Modelo: Moderado'))
                 else:
                     A.success(Idioma.traducao('Modelo: Conservador'))
                 A.success(
                     Idioma.traducao('1ª entrada: %') + '{} | ' +
                     Idioma.traducao('Valor: $') + '{}', self.percent,
                     round(self.ent_valor1, 2))
             A.warning(
                 'WIN %{} - ' +
                 Idioma.traducao('Parar de operar quando atingir: $') +
                 '{}', self.stopgain, round(C.instance().win_limit, 2))
             A.warning(
                 'LOSS %{} - ' +
                 Idioma.traducao('Parar de operar quando atingir: $') +
                 '{}', self.stoploss, round(C.instance().stop_limit, 2))
             print('Versão: ' + self.versaoapp)
             print(Idioma.traducao('Tipo de conta:'), self.tipoconta)
             print(Idioma.traducao('Parâmetros iniciais:'))
             print(Idioma.traducao('Quantidade de gales:'), self.qtdgales)
             print(Idioma.traducao('Payout mínimo:'), self.payoutmin)
             if self.prestop:
                 print(Idioma.traducao('Pré-Stop Loss: Ligado'))
             if self.esperarIQ:
                 print(Idioma.traducao('Resultado Resp. IQ'))
             else:
                 print(Idioma.traducao('Resultado por Taxas'))
             print('Delay: ', self.delay)
             if self.priorid == 0:
                 print(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Maior Payout'))
             elif self.priorid == 1:
                 print(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Digital'))
             elif self.priorid == 2:
                 print(
                     Idioma.traducao('Prioridade') + ': ' +
                     Idioma.traducao('Binárias'))
             if self.naonoticia:
                 print(Idioma.traducao('Não operar em notícia'))
             if self.tendusar:
                 if self.tendemasma:
                     print(
                         Idioma.traducao('Não Operar Contra') + ': ' +
                         Idioma.traducao('Usar EMA5 + SMA20'))
                 else:
                     print(
                         Idioma.traducao('Não Operar Contra') + ': ' +
                         Idioma.traducao('Quant. Velas') + ': ' +
                         str(self.tendvelas))
             if not self.usarsoros:
                 print(Idioma.traducao('Entradas fixas:'))
                 print(Idioma.traducao('Entrada: $'),
                       round(self.ent_valor1, 2))
                 if self.ent_gale1 > 0:
                     print(Idioma.traducao('Gale 1: $'),
                           round(self.ent_gale1, 2))
                 if self.ent_gale2 > 0:
                     print(Idioma.traducao('Gale 2: $'),
                           round(self.ent_gale2, 2))
             else:
                 print('Soros:')
                 if self.modelo == 'A':
                     print(Idioma.traducao('Modelo: Agressivo'))
                 elif self.modelo == 'M':
                     print(Idioma.traducao('Modelo: Moderado'))
                 else:
                     print(Idioma.traducao('Modelo: Conservador'))
                 print((Idioma.traducao('1ª entrada: %') + '{0} | ' +
                        Idioma.traducao('Valor: $') + '{1}').format(
                            self.percent, round(self.ent_valor1, 2)))
             self.View.janela['valorinic'].update(
                 value=(round(self.valorinicial, 2)))
             self.View.janela['saldoatual'].update(
                 value=(C.instance().balance))
             self.View.janela['stopgainp'].update(value=(self.stopgain))
             self.View.janela['stopgainv'].update(
                 value=(round(C.instance().win_limit, 2)))
             self.View.janela['stoplossp'].update(value=(self.stoploss))
             self.View.janela['stoplossv'].update(
                 value=(round(C.instance().stop_limit, 2)))
             self.View.janela.Refresh()
             if not self.usarsoros:
                 self.valorinicial = 0
             C.instance().sorosgale.config_ini(self.valorinicial,
                                               self.percent, self.modelo)
             return True
     return False