def test_Candle(self): #login I_want_money = IQ_Option(email, password) I_want_money.change_balance("PRACTICE") I_want_money.reset_practice_balance() self.assertEqual(I_want_money.check_connect(), True) #start test binary option ALL_Asset = I_want_money.get_all_open_time() if ALL_Asset["turbo"]["EURUSD"]["open"]: ACTIVES = "EURUSD" else: ACTIVES = "EURUSD-OTC" I_want_money.get_candles(ACTIVES, 60, 1000, time.time()) #realtime candle size = "all" I_want_money.start_candles_stream(ACTIVES, size, 10) I_want_money.get_realtime_candles(ACTIVES, size) I_want_money.stop_candles_stream(ACTIVES, size)
def test_binary_option(self): #login I_want_money = IQ_Option(email, password) I_want_money.change_balance("PRACTICE") I_want_money.reset_practice_balance() self.assertEqual(I_want_money.check_connect(), True) #start test binary option ALL_Asset = I_want_money.get_all_open_time() if ALL_Asset["turbo"]["EURUSD"]["open"]: ACTIVES = "EURUSD" else: ACTIVES = "EURUSD-OTC" Money = 1 ACTION_call = "call" #or "put" expirations_mode = 1 check_call, id_call = I_want_money.buy(Money, ACTIVES, ACTION_call, expirations_mode) self.assertTrue(check_call) self.assertTrue(type(id_call) is int) I_want_money.sell_option(id_call) ACTION_call = "put" check_put, id_put = I_want_money.buy(Money, ACTIVES, ACTION_call, expirations_mode) self.assertTrue(check_put) self.assertTrue(type(id_put) is int) I_want_money.sell_option(id_put) I_want_money.check_win_v2(id_put) I_want_money.get_binary_option_detail() I_want_money.get_all_profit() isSuccessful, dict = I_want_money.get_betinfo(id_put) self.assertTrue(isSuccessful) I_want_money.get_optioninfo(10)
return int(100 * a[par]['turbo']) elif tipo == 'digital': API.subscribe_strike_list(par, timeframe) while True: d = API.get_digital_current_profit(par, timeframe) if d != False: d = int(d) break time.sleep(1) API.unsubscribe_strike_list(par, timeframe) return d par = API.get_all_open_time() for paridade in par['turbo']: if par['turbo'][paridade]['open'] == True: print('[ TURBO ]: ' + paridade + ' | Payout: ' + str(payout(paridade, 'turbo'))) print('\n') for paridade in par['digital']: if par['digital'][paridade]['open'] == True: print('[ DIGITAL ]: ' + paridade + ' | Payout: ' + str(payout(paridade, 'digital'))) # Retorna o histórico, para pegar o histórico do digital, deve ser colocado 'digital-option' e para pegar binario, # deve ser colocado 'turbo-option'
def popularAtivos(self,API:IQ_Option): lista = API.get_all_open_time() payouts = API.get_all_profit()
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
int(dad[14]), int(dad[19]), int(dad[24]), int(dad[29]) ] #Timeframe dos sinais horario = [ str(dad[5]), str(dad[10]), str(dad[15]), str(dad[20]), str(dad[25]), str(dad[30]) ] #Horário das entradas #Dados da terceira entrada ConfirmAsset = dados.get_all_open_time( ) #Pega os dados de Todos os ativos abertos para negociação contador = 0 #Faz a contagem e a passagem de payout = CalculoPayout(str(par[contador]), tipo, int(timeframe[contador])) #Calcula o payout f = '%H:%M:%S' #É o formato em que a string de horario vai se transformar m = '00:00:15' #É o tempo que será subtraido do horario , no caso 15 segundos print(tend(par[contador], timeframe[contador])) StopWin = 3 StopLoss = 3 ResultadoF = 0 print('Começando a execução ! ') print('\n') while contador != 6: moment = ( datetime.strptime(horario[contador], f) - datetime.strptime(m, f)
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()
API.set_max_reconnect(5) API.change_balance(ACCOUNT) while True: if API.check_connect() == False: print('Not connected.') API.connect() else: print('Connected.') break time.sleep(1) print(API.get_balance()) all_assets = API.get_all_open_time() profits = API.get_all_profit() data = 'closed' if all_assets['binary'][asset]['open']: amounts = [] assets = [] actions = [] expiration_times = [] digitals = [] id_list = [] amounts.append(50) assets.append(asset) actions.append('put') expiration_times.append(15) id_list=API.buy_multi(amounts,assets,actions,expiration_times)
account : ['REAL', 'PRACTICE'] ''' import json from iqoptionapi.stable_api import IQ_Option data = json.load(open('credentials.json')) username = data['email'] password = data['password'] Iq = IQ_Option(username, password) print('logging in...') check, reason = Iq.connect() #connect to iqoption print('login:'******'SUCCESSFUL' if check else 'FAILED') assert check goal = 'EURUSD' ALL_Asset = Iq.get_all_open_time() if ALL_Asset["turbo"][goal]["open"]: goal = goal else: goal = goal + '-OTC' print() print('Goal =', goal) size = 60 * 60 * 4 maxdict = 10000 start = time.time() Iq.start_candles_stream(goal, size, maxdict) candles = Iq.get_realtime_candles(goal, size) Iq.stop_candles_stream(goal, size) end = time.time() print() print('len:', len(list(candles.values())))
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] #Exibição de alguns dados do perfil na IQ Option #print('Saldo na conta: ',API.get_balance()) #print(x['name']) #print(x['nickname']) #print(x['currency']) #print('Data de cadastro na IQ Option: ',timestamp_converter(x['created'])) par = API.get_all_open_time() #Pega as moedas que estão abertas no momento def payout( par, tipo, timeframe=1 ): #Função que puxa a moeda, tipo e payout de acordo com tempo (1m,5m,15m) if tipo == 'turbo': #Binária a = API.get_all_profit() return int(100 * a[par]['turbo']) elif tipo == 'digital': #Digital API.subscribe_strike_list(par, timeframe) while True: d = API.get_digital_current_profit(par, timeframe)
from iqoptionapi.stable_api import IQ_Option import logging import random logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') I_want_money = IQ_Option("*****@*****.**", "aswdkl;123") I_want_money.connect() #connect to iqoption ALL_Asset = I_want_money.get_all_open_time() #check if open or not print(ALL_Asset["forex"]["EURUSD"]["open"]) print(ALL_Asset["cfd"]["FACEBOOK"]["open"]) #Stock,Commodities,ETFs print(ALL_Asset["crypto"]["BTCUSD-L"]["open"]) print(ALL_Asset["digital"]["EURUSD-OTC"]["open"]) #Binary have two diffenence type:"turbo","binary" print(ALL_Asset["turbo"]["EURUSD-OTC"]["open"]) print(ALL_Asset["binary"]["EURUSD-OTC"]["open"]) #!!!! exception "" print(ALL_Asset["binary"]["not exist asset"] ["open"]) #it will return "{}" a None of the dict #!!!!print all!!!! for type_name, data in ALL_Asset.items(): for Asset, value in data.items(): print(type_name, Asset, value["open"])
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()))
import time import requests from bs4 import BeautifulSoup from selenium import webdriver from iqoptionapi.stable_api import IQ_Option dados = IQ_Option('*****@*****.**','A7Kmx1q2w3e') dados.connect() if dados.check_connect(): print('Conectado com sucesso ! ') else: print('Falha na conexão. Tente novamente! ') OpenAssets = dados.get_all_open_time() #Pega os dados na corretora de ativos abertos ativos = ['USD/JPY','USD/CAD','USD/CHF','EUR/USD','EUR/AUD','EUR/NZD','EUR/GBP','EUR/JPY','EUR/CAD','AUD/JPY','AUD/USD','AUD/CAD','GBP/USD','GBP/AUD','GBP/JPY','GBP/CAD','GBP/NZD','CAD/JPY','CAD/CHF'] print('Quantidade de ativos que eu pré determinei : ',len(ativos)) ativosF = ['USDJPY','USDCAD','USDCHF','EURUSD','EURAUD','EURNZD','EURGBP','EURJPY','EURCAD','AUDJPY','AUDUSD','AUDCAD','GBPUSD','GBPAUD','GBPJPY','GBPCAD','GBPNZD','CADJPY','CADCHF'] AtivosAbertos = [] for a in range(19): #Seleciona os ativos abertos de acordo com a lista acima e if OpenAssets['turbo'][ativosF[a]]['open']: AtivosAbertos.append(ativos[a]) print('Ativos abertos : ',len(AtivosAbertos) + 1)#Mostra a quantidade de ativos abertos print(AtivosAbertos) driver = webdriver.Chrome('/Users/Richeli/Desktop/iqoption/chromedriver') #Lozaliza os dados do navegador driver.get('http://br.investing.com/technical/pivot-points') #Site desejado