d1 = dados[0] d2 = dados[1] d3 = dados[2] d4 = dados[3] #rint(d1, d2, d3, d4) dia = dados[0] hora = dados[1] par = dados[2] direcao = dados[3] entrada = float(conf['valor_entrada']) fator_gale = float(conf['fator_gale']) timeframe = 1 # Entradas na digital #print('Esperando Entrada') if dia_hora(dia, hora): print('ENTRADA', sinal) lista.remove(lista[c]) id = API.buy_digital_spot(par, entrada, direcao.lower(), timeframe) # direção caixa baixa if id == 'error': c += 1 continue if isinstance(id, int): threading.Thread(target=status_entrada, args=(id, API, par, entrada, direcao, timeframe, fator_gale)).start() c += 1 time.sleep(1)
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
break time.sleep(1) def timestamp_converter(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 str(hora.astimezone(tz.gettz('America/Sao Paulo')))[:-6] par = 'EURUSD-OTC' status, id = API.buy_digital_spot(par, 5, 'CALL', 1) vela = API.get_candles(par, 60, 1, time.time()) valorAtual = str(vela[0]['close']) x = float(int(vela[0]['to'])) x = x - 1 x = timestamp_converter(x) lcltime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') while (x != lcltime): lcltime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') else: vela = API.get_candles(par, 60, 1, time.time()) valorDeFechamento = str(vela[0]['close']) if valorDeFechamento < valorAtual: status, id = API.buy_digital_spot(par, 5, 'CALL', 1)
if API.check_connect(): print(' Conectado com sucesso!') else: print(' Erro ao conectar') input('\n\n Aperte enter para sair') sys.exit() porcentagem_lucro = 10 entrada = 10.0 par = 'EURUSD' timeframe = 1 valor_minimo = round(float(entrada) * (float(porcentagem_lucro / 100)), 2) API.subscribe_strike_list(par, timeframe) status, id = API.buy_digital_spot(par, entrada, 'put', timeframe) time.sleep(2) while API.get_async_order(id)['position-changed']['msg']['status'] == 'open': vpv = round(API.get_digital_spot_profit_after_sale(id), 2) print('Atual: $' + str(vpv) + ' - Minimo para venda: $' + str(valor_minimo)) if vpv > valor_minimo: print('Fechando operação') API.close_digital_option(id) break time.sleep(0.3)
erroCont = 0 erro = 0 doji = 0 par = pares[numberRandom] acertividade = 0 #compra_status, id_compra = API.buy_digital_spot(pares, valor, entrada, tempo ) while True: print("O par que esta sendo comprado: ", par) #Compra compra_status, id = API.buy_digital_spot(par, valor, entrada, tempo) print("Status da compra: ", compra_status, id) print("Aguardando resultado...") while compra_status == False: numberRandom = randint(0, 7) par = pares[numberRandom] compra_status, id = API.buy_digital_spot(par, valor, entrada, tempo) if compra_status == True: break #result = API.check_win_v3(id) while True: check, win = API.check_win_digital_v2(id) if check == True: break
valor_entrada = 0 valor = 0 lucro = 0 # Realiza 5 entradas baseado na ultima previsão do modelo, após isso realiza uma nova previsão while True: ids = [] df = preview().head(5) for row in df.itertuples(): valor_entrada = float(int(banca()) // 10) bs = row[0] sinal = row[1] while True: tempo_servidor = timestamp_converter(API.get_server_timestamp()) if tempo_servidor + timedelta(seconds=3) == sinal: valor_entrada = float(int(banca()) // 10) print('Entrou', bs, sinal, '\nEntrada:', valor_entrada) status, id = API.buy_digital_spot(par, valor_entrada, bs, 1) ids.append(id) time.sleep(1) if tempo_servidor > sinal: print('Próximo Sinal') break
class MHI: def __init__(self, email, password): self.API = IQ_Option(email, password) self.config = configuration.getConfig() self.connection() def connection(self): self.API.connect() self.API.change_balance('PRACTICE') if self.API.check_connect(): print(' Conectado com sucesso!') else: print(' Erro ao conectar') sys.exit() def stop(self, lucro): if lucro <= float(-1 * abs(self.config['stop_loss'])): print('Stop Loss batido!') sys.exit() if lucro >= float(abs(self.config['stop_gain'])): print('Stop Gain Batido!') sys.exit() def Martingale(self, valor, payout): lucro_esperado = valor * payout perca = float(valor) while True: if round(valor * payout, 2) > round( abs(perca) + lucro_esperado, 2): return round(valor, 2) break valor += 0.01 def Payout(self, par=''): if par.strip() != '': self.API.subscribe_strike_list(par, 1) while True: d = self.API.get_digital_current_profit(par, 1) if d != False: d = round(int(d) / 100, 2) break time.sleep(1) self.API.unsubscribe_strike_list(par, 1) return d def isTime(self): minutos = float(((datetime.now()).strftime('%M.%S'))[1:]) return True if (minutos >= 4.58 and minutos <= 5) or minutos >= 9.58 else False def getColors(self): velas = self.API.get_candles(self.config['par'], 60, 3, time.time()) retorno = '' for i in range(len(velas)): if velas[i]['open'] < velas[i]['close']: retorno += 'g' elif velas[i]['open'] > velas[i]['close']: retorno += 'r' else: retorno += 'd' return retorno def getDirection(self, cores): dir = False if cores.count('g') > cores.count('r') and cores.count('d') == 0: dir = ('put' if self.config['tipo_mhi'] == 1 else 'call') if cores.count('r') > cores.count('g') and cores.count('d') == 0: dir = ('call' if self.config['tipo_mhi'] == 1 else 'put') return dir def buyParity(self, dir): if self.config['operacao'] == 1: return self.API.buy_digital_spot(self.config['par'], self.config['valor_entrada'], dir, 1) else: return self.API.buy(self.config['valor_entrada'], self.config['par'], dir, 1) def finishTrade(self, id): finish = (True, 0) if self.config['operacao'] == 1: finish = self.API.check_win_digital_v2(id) else: finish = (True, self.API.check_win_v3(id)) return finish def startTrade(self, dir, payout): lucro = 0 print('iniciando trader') self.config['valor_entrada'] = self.config['valor_entrada_b'] for i in range(self.config['martingale']): if i > 2: dir = 'put' if dir == 'call' else 'call' buy, id = self.buyParity(dir) if buy: print('Compra efetuada') while True: try: finish, valor = self.finishTrade(id) except: finish = True valor = 0 if finish: print('Operaçao Finalizada') valor = valor if valor > 0 else float( -1 * abs(self.config['valor_entrada'])) lucro += round(valor, 2) self.config['valor_entrada'] = self.Martingale( self.config['valor_entrada'], payout) self.stop(lucro) break if valor > 0: break def start(self): self.config['valor_entrada_b'] = self.config['valor_entrada'] print("Aguardando o horario.") while True: horas = self.isTime() payout = self.Payout(self.config['par']) if payout < (self.config['payout'] / 100): print(f'Payout abaixo do minimo permitido: {payout}') break if horas: cores = self.getColors() dir = self.getDirection(cores) if dir: self.startTrade(dir, payout) time.sleep(0.5)
cores = velas[0] + ' ' + velas[1] + ' ' + velas[2] print(cores) if cores.count('g') > cores.count('r') and cores.count('d') == 0: dir = ('put' if tipo_mhi == 1 else 'call') if cores.count('r') > cores.count('g') and cores.count('d') == 0: dir = ('call' if tipo_mhi == 1 else 'put') if dir: print('Direção:', dir) valor_entrada = valor_entrada_b for i in range(martingale): status, id = API.buy_digital_spot( par, valor_entrada, dir, 1) if operacao == 1 else API.buy( valor_entrada, par, dir, 1) if status: while True: try: status, valor = API.check_win_digital_v2( id ) if operacao == 1 else True, API.check_win_v3(id) except: status = True valor = 0 if status: valor = valor if valor > 0 else float( '-' + str(abs(valor_entrada)))
if datual == tempo_sinal: hora_sinal_entrada = tempo_sinal ativo_sinal_entrada = ativo_sinal valor_sinal_entrada = 10 direcao_sinal_entrada = direcao_sinal tempo_sinal_entrada = 1 print( '\nAtivo: ' + str(ativo_sinal_entrada) + '\nHora: ' + str(hora_sinal_entrada) + '\nDireção: ' + str(direcao_sinal_entrada) + '\n--------------------------------------------------------------------------------\n ENTROU NA OPERAÇAO\n--------------------------------------------------------------------------------' ) status, id = API.buy_digital_spot(ativo_sinal_entrada, valor_sinal_entrada, 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()
class Gale: def __init__(self, user, password, valor, tempo, conta): self.API = IQ_Option(user, password) self.id_compra = '' self.loss = 0 self.win = 0 self.value = valor self.entrada = 'put' self.time = tempo self.account = conta self.pares = [ 'EURUSD-OTC', 'AUDCAD-OTC', 'NZDUSD-OTC', 'USDCHF-OTC', 'GBPUSD-OTC', 'EURJPY-OTC' ] self.par = self.pares[self.RandomNumber()] # Conectando na conta. Retorna se foi feito com sucesso ou não def Connection(self): self.API.connect() if self.API.connect(): self.Account() return print('Successfully connected :D') else: return print('Conection Error D:') # Retorna tipo de conta, se é real ou de pratica def Account(self): return self.API.change_balance(self.account) # Gerando um número random def RandomNumber(self): numberRandom = randint(0, len(self.pares) - 1) return numberRandom # Recebe valor, entrada, tempo def Compra(self): print('Make a buy...') compra_status, self.id_compra = self.API.buy_digital_spot( self.par, self.value, self.entrada, self.time) if compra_status == False: print('Buy Again') self.par = self.pares[self.RandomNumber()] self.Compra() else: print('waiting for the result of the order...') check, result = self.API.check_win_digital_v2(self.id_compra) if result > 0: self.winResult() else: self.lossResult() # Retorna se bateu a meta ou não def winResult(self): self.win += 1 self.loss = 0 if self.win == 10: return print("Meta batida ;D") self.par = self.pares[self.RandomNumber()] self.Compra() # Faz o gale e ainda entra novamente até acertar ou falhar def lossResult(self): self.loss += 1 if self.loss == 3: return print("Hit :/") else: newValue = self.galeValue() compra_status, self.id_compra = self.API.buy_digital_spot( self.par, newValue, self.entrada, self.time) check, newResult = self.API.check_win_digital_v2(self.id_compra) if newResult < 0: self.lossResult() else: newValue = self.value self.winResult() # Retorna o novo valor, fazendo o Maringale def galeValue(self): newValue = self.value newValue = (newValue * 1.15) * 2 return newValue # Verificar e retorna o valor do resultado da operação def resultVerification(self, id): self.API.check_win_digital_v2(self.id_compra) return self.API.check_win_v3(self.id_compra)
from iqoptionapi.stable_api import IQ_Option import time import random Iq = IQ_Option("*****@*****.**", "aswdkl;123") Iq.connect() #connect to iqoption ACTIVES = "EURUSD" duration = 1 #minute 1 or 5 amount = 1 action = "call" #put print(type(ACTIVES)) print(type(duration)) print(type(amount)) print(type(action)) print(Iq.buy_digital_spot(ACTIVES, amount, action, duration))
def testfunc(jobid, email, password, instrumentid_tmp, instrumenttype_tmp, direction_tmp, leverage_tmp, starttimehour_tmp, starttimeminute_tmp, stoptimehour_tmp, stoptimeminute_tmp, day_str, amount_tmp): print("{}: JobId executing... current time {}".format( jobid, datetime.now())) print("{}: JobId parameters " "{}: email" "{}: password" "instrumentId: {} " "instrumentType: {} " "diection_tmp: {} " "leverage_tmp: {}" "starttimehour_tmp: {}" "starttimeminute_tmp: {}" "stoptimehour_tmp: {}" "stoptimeminute_tmp: {}" "day_str: {}" "amount_tmp: {}".format(jobid, email, password, instrumentid_tmp, instrumenttype_tmp, direction_tmp, leverage_tmp, starttimehour_tmp, starttimeminute_tmp, stoptimehour_tmp, stoptimeminute_tmp, day_str, amount_tmp)) if instrumenttype_tmp == 'BINARY' or instrumenttype_tmp == 'binary': print("In binary") Iq = IQ_Option(email=email, password=password) # Iq = IQ_Option("*****@*****.**", "aswdkl;123") Iq.connect() print(Iq.connect()) # Money = 1 # ACTIVES = "EURUSD" Money = int(amount_tmp) ACTIVES = instrumentid_tmp if direction_tmp == "BUY": ACTION = "call" # or "put" else: ACTION = "put" expirations_mode = 1 check, id = Iq.buy(Money, ACTIVES, ACTION, expirations_mode) if check: print("{}: JobId {} {} at {}".format(jobid, ACTIVES, ACTION, datetime.now())) else: print("buy fail") elif instrumenttype_tmp == 'DIGITAL' or instrumenttype_tmp == 'digital': print("In digital!") Iq = IQ_Option(email=email, password=password) # Iq = IQ_Option("*****@*****.**", "aswdkl;123") Iq.connect() print(Iq.connect()) # Money = 1 # ACTIVES = "EURUSD" Money = int(amount_tmp) ACTIVES = str(instrumentid_tmp) if direction_tmp == "BUY": ACTION = "call" # or "put" else: ACTION = "put" DURATION = 1 print("Money: {} ACTIVES: {} ACTION: {} expiration_mode: {}".format( Money, ACTIVES, ACTION, DURATION)) # print(type(Money)) # print(type(ACTIVES)) # print(type(ACTION)) # print(type(DURATION)) check, id = Iq.buy_digital_spot(ACTIVES, Money, ACTION, DURATION) if check: print("{}: JobId {} {} at {}".format(jobid, ACTIVES, ACTION, datetime.now())) else: print("buy fail") else: Iq = IQ_Option(email=email, password=password) # Iq = IQ_Option("*****@*****.**", "aswdkl;123") Iq.connect() print(Iq.connect()) print("__For_Forex_Stock_Commodities_Crypto_ETFs") instrument_type = instrumenttype_tmp.lower() print(instrument_type) instrument_id = instrumentid_tmp if direction_tmp == "BUY": side = "buy" # or "put" else: side = "sell" amount = int(amount_tmp) leverage = int(leverage_tmp) type = "market" limit_price = None stop_price = None stop_lose_kind = "percent" stop_lose_value = 95 take_profit_kind = None take_profit_value = None use_trail_stop = True auto_margin_call = False use_token_for_commission = False print("instrument_type: {}," "instrument_id: {}," "side: {}," "leverage: {}," "type: {}," "limit_price: {}," "stop_price: {}," "stop_lose_value: {}," "take_profit_value: {}," "take_profit_kind: {}," "use_trail_stop: {}," "auto_margin_call: {}," "use_token_for_commission: {}".format( instrument_type, instrument_id, side, amount, leverage, type, limit_price, stop_price, stop_lose_value, stop_lose_kind, take_profit_value, take_profit_kind, use_trail_stop, auto_margin_call, use_token_for_commission)) check, id = 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) # if check: # print(check) # else: # print("no check") if check: print("{}: JobId {} {} at {}".format(jobid, instrument_type, instrument_id, datetime.now())) else: print("buy fail") while Iq.get_async_order(id) == None: pass order_data = Iq.get_async_order(id) print(Iq.get_async_order(id))
print('\n\nIniciando operação!') print('Verificando cores..', end='') velas = API.get_candles(par, intervalo, 5, time.time()) cores = cores_velas(velas) # define as cores das velas Ex.: g r g print(cores) direcao = direcao_entrada( cores) #define a posição de compra se for call ou put if direcao: print('DIREÇÃO:', direcao) valor_entrada = valor_entrada_b for i in range(martingale): status, id = API.buy_digital_spot(par, montante, direcao, 1) if status: while True: status, valor = API.check_win_digital_v2(id) if status: valor = valor if valor > 0 else float( '-' + str(abs(valor_entrada))) print('Resultado operação: ', end='') print( Back.GREEN + 'WIN /' if valor > 0 else Back.RED + 'LOSS /', round(valor, 2), '/', round(lucro, 2), ('/ ' + str(i) + ' GALE' if i > 0 else '')) valor_entrada = Martingale(valor_entrada, payout)
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") if act == "put": act = "call" else: act = "put" else: print("win")
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()))