def get_CandleResults(lista): returnedList = [] init(autoreset=True) API = IQ_Option('*****@*****.**', 'Fh006131__') check, reason=API.connect()#connect to iqoption API.change_balance('PRACTICE') # while True: if API.check_connect() == False: print('Erro ao se conectar') else: for l in lista: l = l.split(',') horario = datetime.strptime(l[0] + ":00", "%Y-%m-%dT%H:%M:%S") horario = datetime.timestamp(horario) if l[3] == "M5": velas = API.get_candles(l[1],300,3,int(horario)) elif l[3] == "M15": velas = API.get_candles(l[1],900,3,int(horario)) else: print ('Dado não lido. Incompatível!') for v in range(len(velas)): if int(velas[v]['from']) == int(horario): dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji' if dir == l[2].lower(): returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅') print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN') else: if int(velas[v]['from']) == int(horario): dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji' if dir == l[2].lower(): returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅1️⃣') print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN') else: if int(velas[v]['from']) == int(horario): dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji' if dir == l[2].lower(): returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅2️⃣') print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN') else: returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-❌') print(l[0],l[1],l[2],l[3],'|', Fore.RED + 'LOSS')
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)
stop_loss = float(input(' Indique o valor de Stop Loss: ')) stop_gain = float(input(' Indique o valor de Stop Gain: ')) lucro = 0 payout = Payout(par) while True: minutos = float(((datetime.now()).strftime('%M.%S'))[1:]) entrar = True if (minutos >= 4.58 and minutos <= 5) or minutos >= 9.58 else False print('Hora de entrar?', entrar, '/ Minutos:', minutos) if entrar: print('\n\nIniciando operação!') dir = False print('Verificando cores..', end='') velas = API.get_candles(par, 60, 3, time.time()) velas[0] = 'g' if velas[0]['open'] < velas[0][ 'close'] else 'r' if velas[0]['open'] > velas[0]['close'] else 'd' velas[1] = 'g' if velas[1]['open'] < velas[1][ 'close'] else 'r' if velas[1]['open'] > velas[1]['close'] else 'd' velas[2] = 'g' if velas[2]['open'] < velas[2][ 'close'] else 'r' if velas[2]['open'] > velas[2]['close'] else 'd' 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')
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) print(status)
money = float(input("Qual o valor da entrada: ")) martingale = int(input('Indique a quantia de martingales: ')) stop_loss = float(input('Indique o valor de Stop Loss: ')) stop_gain = float(input('Indique o valor de Stop Gain: ')) lucro = 0 print("\nAguandando a Hora para fazer a entrada !!! ") martingale += 1 hora_moeda = arquivo() contador = 0 for x in hora_moeda: split = x.split(',') hora = split[0] moeda = split[1] par = str(split[2]) velas = API.get_candles(moeda, (int(timeframe) * 60), 100, time.time()) ultimo = round(velas[0]['close'], 4) primeiro = round(velas[-1]['close'], 4) diferenca = abs(round(((ultimo - primeiro) / primeiro) * 20, 3)) tendencia = "CALL" if ultimo < primeiro and diferenca > 0.01 else "PUT" if ultimo > primeiro and diferenca > 0.01 else "False" lcltime = datetime.now().strftime('%H:%M') print("Tendencia: ", tendencia) print("Entrada do Sinal: ", par) while (hora != lcltime): lcltime = datetime.now().strftime('%H:%M') else: Money = money ACTIVES = moeda ACTION = par expirations_mode = timeframe valor = 0.0
if entrar: print("\n\nIniciando Trade!", "\nData:", str(teste)[:-6]) if valor > 0: # Wins consecutivos adicionam metade do Gain na próxima entrada valor_entrada = float(int(banca()) // 10) + round(valor // 2, 2) else: valor_entrada = float(int(banca()) // 10) print("Entrada:", valor_entrada) dir = False inverte = False print("Verificando cores..") # Aplica Estratégia MHI Potencializada velas = API.get_candles(par, 60, 10, API.get_server_timestamp()) velas[2] = ("g" if velas[2]["open"] < velas[2]["close"] else "r" if velas[2]["open"] > velas[2]["close"] else "d") velas[3] = ("g" if velas[3]["open"] < velas[3]["close"] else "r" if velas[3]["open"] > velas[3]["close"] else "d") velas[4] = ("g" if velas[4]["open"] < velas[4]["close"] else "r" if velas[4]["open"] > velas[4]["close"] else "d") velas[5] = ("g" if velas[5]["open"] < velas[5]["close"] else "r" if velas[5]["open"] > velas[5]["close"] else "d") velas[6] = ("g" if velas[6]["open"] < velas[6]["close"] else "r" if velas[6]["open"] > velas[6]["close"] else "d") velas[7] = ("g" if velas[7]["open"] < velas[7]["close"] else "r" if velas[7]["open"] > velas[7]["close"] else "d") velas[8] = ("g" if velas[8]["open"] < velas[8]["close"] else "r" if velas[8]["open"] > velas[8]["close"] else "d")
from iqoptionapi.stable_api import IQ_Option import time, json, logging, configparser arquivo_user = configparser.RawConfigParser() arquivo_user.read('config_user.txt') API = IQ_Option(arquivo_user.get('USER', 'user'), arquivo_user.get('USER', 'password')) API.connect() API.change_balance('PRACTICE') # PRACTICE / REAL if API.check_connect(): print('\n\nConectado com sucesso') else: print('\n Erro ao se conectar') sys.exit() par = 'EURUSD' timeframe = 5 velas = API.get_candles(par, (int(timeframe) * 60), 20, time.time()) ultimo = round(velas[0]['close'], 4) primeiro = round(velas[-1]['close'], 4) diferenca = abs( round( ( (ultimo - primeiro) / primeiro ) * 100, 3) ) tendencia = "CALL" if ultimo < primeiro and diferenca > 0.01 else "PUT" if ultimo > primeiro and diferenca > 0.01 else False print(tendencia)
import time from iqoptionapi.stable_api import IQ_Option import json import logging # logging level logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') Iq = IQ_Option("*****@*****.**", "aswdkl;123") # connect to iqoption check, reason = Iq.connect() print(check, reason) # connect to iq option Iq.connect() goal = "EURUSD" print("get candles") iqCandles = Iq.get_candles(goal, 60, 111, time.time()) iqCandles_json = json.dumps(iqCandles) print(type(iqCandles)) print(type(iqCandles_json)) print(iqCandles) print(iqCandles_json)
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')
from iqoptionapi.stable_api import IQ_Option from dotenv import load_dotenv from datetime import datetime import time import os load_dotenv() Iq=IQ_Option(os.getenv("USER"),os.getenv("PASS")) Iq.connect()#connect to iqoption while True: minutos = float(((datetime.now()).strftime('%M.%S'))) print(minutos) time.sleep(60) velas=Iq.get_candles("EURUSD", 300, 5, time.time()) print(velas) for i in range(5): velas[i] = 'g' if velas[i]['open'] < velas[i]['close'] else 'r' if velas[i]['open'] > velas[i]['close'] else 'd' cores = f'{velas[0]} {velas[1]} {velas[2]} {velas[3]} {velas[4]}' print(cores)
primeiro = round(candles[-1]['open'], 4) diferenca = abs( round( ( (ultimo - primeiro) / primeiro ) * 100, 3) ) tendencia = "CALL" if ultimo < primeiro and diferenca > 0.01 else "PUT" if ultimo > primeiro and diferenca > 0.01 else "DOJI" return tendencia print('\n') contator = 0 cont = 0 Contpar = 0 parity = ['AUDCAD','GBPJPY','EURJPY','GBPNZD','EURNZD','EURUSD','CADJPY','EURAUD','EURCAD','GBPAUD','USDJPY'] while Contpar != int(len(parity)): print('Catalogando : ',parity[Contpar],'...') while cont != qtdDias: velas = dados.get_candles(parity[Contpar] , (60*5) , 288 , horario) velas.reverse() for a in velas : res = datetime.fromtimestamp(horario).strftime('%Y-%m-%d %H:%M:%S') YearIn = date(year = int(str(res[0] + res[1] + res[2] + res[3])) , month = int(str(res[5] + res[6])), day = int(str(res[8] + res[9])) ) #Esse formato eu vou usar para retornar o dia da semana que é dateX = date(year = int(str(timezz[0] + timezz[1] + timezz[2] + timezz[3])) , month = int(str(timezz[5] + timezz[6])), day = int(str(timezz[8] + timezz[9])) ) moment = str(res[10] + res[11] + res[12] + res[13] + res[14] + res[15] + res[16] + res[17]) DiasT[contator] = moment diaSemana = YearIn.isoweekday() # Classifica a data em dias da semana de (1 - 7) if diaSemana == 7 or diaSemana == 6 : # Não contabiliza fim de semana horario = horario - 300 else: if a['open'] < a['close']: ContCall[Contpar][contator] = ContCall[Contpar][contator] + 1
def iq_data(): I_want_money = IQ_Option("*****@*****.**", "Secret12345@") goal = "YAHOO" data = I_want_money.get_candles(goal, 10, 60, time.time()) return data
valor_entrada_b = float(montante) print(f"Contratos ativos: {par}") print(f"Duração: {duracao}m") lucro = 0 payout = Payout(par) while True: sleep, minutos, entrar = calcula_intervalo(intervalo) print('Hora de entrar?', entrar, '/ Minutos:', minutos) if entrar: 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:
x1={ ""+str(instrument[i]):{"support":a[0],"resistance":a[1]} } z.update(x1) t1 = time.localtime(time.time()) t1 = t1[3] * 60 + t1[4] t2 = 0 j = 0 print(x1) p = json.dumps(z) p = json.loads(p) while (t2 - t1 <= 15): end_from_time = time.time() d = API.get_candles(instrument[j], 1, 1, end_from_time) d =d[0]['close'] #print(d) rs=data(86400,instrument[j],20) rsi=rsiFunc(rs['Close'].tail(14), n=14) print(instrument[j],rsi[13]) #trend=trendline(index,rs['Close'].tail(6), order=1) if p[''+instrument[j]]['support'] != None: if d<=p[''+instrument[j]]['support'] and rsi[13]>50: print('this instrument',instrument[j]) checker('call', j, instrument,money1,money2,current_money) print('done') if p[''+instrument[j]]['resistance'] != None: if d>=p[''+instrument[j]]['resistance'] and rsi[13]<50: print('this instrument',instrument[j]) checker('put', j, instrument,money1,money2,current_money)
args = parser.parse_args() asset = args.asset or "USDJPY" interval = args.interval or 60 sufix = args.filesufix or "" ## AUTH user = userdata.mainUser Iq = IQ_Option(user["username"], user["password"]) ticks = [] for i in range(2): candles = [] candles = Iq.get_candles(asset, int(interval), 1000, time.time()) cds = [] for candle in list(candles): cd_handle = {} if candle["open"]: cd_handle['open'] = candle["open"] cd_handle['high'] = candle["max"] cd_handle['low'] = candle["min"] cd_handle['close'] = candle["close"] cd_handle['created_at'] = dt.datetime.fromtimestamp( candle["from"]).isoformat() cd_handle['timestamp'] = candle["from"] cd_handle['volume'] = candle["volume"] cds.append(cd_handle) ticks = cds + ticks
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] def banca(): return API.get_balance() ## Pegar até 1000 velas ######################### par = 'EURUSD' vela = API.get_candles(par, 60, 10, time.time()) for velas in vela: print('Hora inicio: ' + str(timestamp_converter(velas['from'])) + ' abertura: ' + str(velas['open'])) ## Pegar mais de 1000 velas ######################### par = 'EURUSD' total = [] tempo = time.time() for i in range(2): X = API.get_candles(par, 60, 1000, tempo) total = X + total tempo = int(X[0]['from']) - 1
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)
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
import time import json, ast, csv from iqoptionapi.stable_api import IQ_Option I_want_money=IQ_Option("*****@*****.**", "Roba2018!") goal="USDZAR" print("get candles") my_candles = I_want_money.get_candles(goal,60,1440,time.time()) print(my_candles) keys = my_candles[0].keys() with open('csvs/usd/usdzar.csv', 'wb') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(my_candles)