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)
def buy_thread(email, senha, paridade, tipo, expiracao, action, valor): conta = IQ_Option(email, senha) conta.connect() conta.change_balance("PRACTICE") if (tipo == 'BINÁRIA'): check, id = conta.buy(valor, paridade, action, expiracao) if check: time.sleep(1) return check if (tipo == 'DIGITAL'): check, id = conta.buy_digital_spot(paridade, valor, action, expiracao) if check: time.sleep(1) return check print(check, id) return 'error check'
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
import random import time import json from iqoptionapi.stable_api import IQ_Option from datetime import datetime print("login...") I_want_money = IQ_Option("*****@*****.**", "zoom3.m.2009") I_want_money.change_balance("REAL") ACTIVES = "EURUSD" ACTION = "call" expirations_mode = 1 force_buy = False cost = 1 optionID = 0 print("") print("Buying option...") print("Cost: ${}".format(cost)) optionID = I_want_money.buy(cost, ACTIVES, ACTION, expirations_mode, force_buy) print(ACTIVES + " - History") print("--------------------------------") print("Option ID: {}".format(optionID)) time.sleep(0) cost = cost + 0.01
timeframe[contador]) == direcao[contador] or tend( par[contador], timeframe[contador] ) != direcao[contador] == "lateralização": print("Sinal a Favor da tendência ! ") while datetime.now().strftime('%H:%M:%S') != horario[ contador]: #Espera até o horario ser correto time.sleep(0.100) a = dados.check_connect() #Checa a conexão if a == False: #Caso a conexão seja perdida ele tenta a reconexão print( 'A conexão foi perdida ! Para evitar perdas o programa será encerrado' ) sys.exit else: #(Quando o horário == horario da entrada) == True a entrada será efetuada! id, status = dados.buy( entrada[contador], par[contador], direcao[contador], timeframe[contador]) #Efetua a entrada print(contador + 1, 'º - ', 'Entrada efetuada -', par[contador], 'R$', entrada[contador], '!') #Informa que a entrada foi efetuada if status: #Se a entrada == True res1, lucro1 = dados.check_win_v3( status) #Checa o resultado da operação if lucro1 > 0: #Caso seja Win print('Win R$ +', ((int(entrada[contador]) * payout) / 100)) contador = contador + 1 ResultadoF = ResultadoF + 1 #Faz a contagem de wins / loss if ResultadoF == StopWin: #Se o stop win for batido ele interrompe a execução do programa print('STOP WIN ! ') sys.exit() #Finaliza o programa
class Helper: PORT = 8888 HOST = '127.0.0.1' thread_list = [] result_row_counter = 0 def login(self,widget_list,email,password,mode,money,expire,msg_label, button,frame): if(button.cget("text") == "Start"): self.main_log_frame = frame; self.email = email.get() self.password = password.get() # [email protected] Dazeface1 self.api = IQ_Option(self.email, self.password) connection_msg = self.api.connect() if connection_msg[0]!=True: err_msg = json.loads(connection_msg[1])["message"] msg_label.config(text=err_msg,fg="#d90f4f") # print(err_msg) # print(json.loads(connection_msg[1])) return else: msg_label.config(text="Connected!",fg="#00bf89") self.account_type = mode.get() self.money = float(str(money.get()).strip()) self.expire_time = float(str(expire.get()).strip()) self.api.change_balance(self.account_type) # self.server_thread = Thread(target=self.start_server) self.server_thread.start() self.change_button(button, widget_list,msg_label) return def checker(self,id,actives): # print("Begin Checking for id: "+str(id)); self.result_row_counter += 1; result = self.api.check_win_v3(id); if float(result) > 0: Label(self.scrollable_frame, font="Arial 10 bold", text=actives+" - ID:"+str(id)+" - WIN! - Amount:"+str(result)+"$", bg="#00bf89", fg="white", padx=0, pady=0, width=50, height=2, anchor='w').pack()#grid(row=self.result_row_counter, column=0, pady=1, sticky="ew") if float(result) ==0: Label(self.scrollable_frame, font="Arial 10 bold", text=actives+" - ID:"+str(id)+" - DRAW!", bg="#e37d00", fg="white", padx=0, pady=0, width=50, height=2, anchor='w').pack()#grid(row=self.result_row_counter, column=0, pady=1, sticky="ew") if float(result) < 0: Label(self.scrollable_frame, font="Arial 10 bold", text=actives+" - ID:"+str(id)+" - LOOSE! - Amount:"+str(result)+"$", bg="#d90f4f", fg="white", padx=0, pady=0, width=50, height=2, anchor='w').pack()#grid(row=self.result_row_counter, column=0, pady=1, sticky="ew") # print(result); def bet(self,action,actives): check,id = self.api.buy(self.money, actives, action, self.expire_time) checkerThred = Thread(target=self.checker, args=[id,actives]) checkerThred.start() def start_server(self): self.running = True self.socket = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM) self.socket.bind((self.HOST,self.PORT)) self.socket.listen(50) # print("client has been connected") while True: if self.running == False: self.socket.close() self.socket = None _thread.exit() break con, adr = self.socket.accept() client_thread = Thread(target=self.onNewCon, args=[con,adr]) client_thread.start() print("newcon"); _thread.exit() return def onNewCon(self,con,adr): while True: print(active_count()) data = con.recv(1024).decode('utf-8').strip().split("|") if self.running == False: self.con.close() _thread.exit() break print(data[0]+" | "+data[1]) actives = str(data[1]) signal = str(data[0]) if signal == "UP": betThread = Thread(target=self.bet, args=["call",actives]) elif signal == "DOWN": betThread = Thread(target=self.bet, args=["put",actives]) else: betThread = False if betThread: betThread.start() def change_button(self, button,widget_list,msg_label): button_text = button.cget('text') if button_text=="Start": button.config(text='Stop') self.disable_widgets(widget_list) elif button_text=="Stop": self.stop_server() button.config(text='Start') msg_label.config(text="Disconnected",fg="#e37d00") self.enable_widgets(widget_list) def disable_widgets(self,widget_list): for widget in widget_list: widget.config(state='disabled') def enable_widgets(self, widget_list): for widget in widget_list: widget.config(state='normal') def stop_server(self): self.running = False try: self.socket self.socket.close() self.socket = None except: pass print("Closed")
input('\n\n Aperte enter para sair') sys.exit() porcentagem_lucro = 10 entrada = 10.0 par = 'AUDCAD-OTC' timeframe = 1 valor_minimo = round(float(entrada) * (float(porcentagem_lucro / 100)), 2) profit = API.get_all_profit() #API.subscribe_strike_list(par, timeframe) #API.get_re print(profit) status, id = API.buy_digital_spot(par, entrada, 'put', timeframe) print(f'{status} {id}') status, id = API.buy(entrada, par, 'put', timeframe) print(f'{status} {id}') ''' #status,id = API.buy_order(1, "BTCUSD", "call", 1) #print('{} id={}'.format(status,id)) instrument_type="binary" instrument_id="EURUSD" side="sell" amount=1.23 leverage=3 type="market" limit_price=None stop_price=None stop_lose_kind="percent" stop_lose_value=95 take_profit_kind=None
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
while True: minutos = float(((datetime.now()).strftime('%M'))) segundos = float(((datetime.now()).strftime('%S'))) # print(">> " + str(segundos) ) # f.write(str(segundos)+"\n") if (segundos == 26): f.write("-------Entrando ------- " + par + " " + modo + "\n") f.write(datetime.now().strftime("%d/%m/%Y %H:%M:%S") + "\n") dir = False velas = API.get_candles(par, 60, 4, time.time()) vela = 'g' if velas[0]['open'] < velas[0][ 'close'] else 'r' if velas[0]['open'] > velas[0]['close'] else 'd' dir = 'put' if vela == 'g' else 'call' if dir: status, id = API.buy(valor_entrada_b, par, dir, 1) f.write(">> dir: " + dir + "\n") time.sleep(30) result = API.check_win_v3(id) f.write("Rodada: " + str(jogada) + "\n") f.write("Entrada: " + str(valor_entrada_b) + " martingale: " + str(martingale) + "\n") f.write("Resultado: " + result["option-closed"]["msg"]["result"] + "\n") if (result["option-closed"]["msg"]["result"] == 'loose'): looses = looses + 1 lucro = lucro - valor_entrada_b if martingale < 2: valor_entrada_b = valor_entrada_b * 2 martingale = martingale + 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)
tipo = 'live-deal-digital-option' # live-deal-binary-option-placed timeframe = 'PT' + config['timeframe'] + 'M' # PT5M / PT15M old = 0 # Captura o Payout config['payout'] = float(payout(config['paridade'], 'digital', int(config['timeframe'])) / 100) API.subscribe_live_deal(tipo, config['paridade'], timeframe, 10) while True: trades = API.get_live_deal(tipo, config['paridade'], timeframe) if len(trades) > 0 and old != trades[0]['user_id'] and trades[0]['amount_enrolled'] >= float( config['valor_minimo']): API.buy(trades[0]['amount_enrolled'],config['paridade'],trades[0]['instrument_dir'], -1) # API.buy_by_raw_expirations(trades[0]['amount_enrolled'],config['paridade'],trades[0]['instrument_dir'],'binary',trades[0]['instrument_expiration']) # API.buy(30,'EURJPY', 'call', -1) # API.buy_digital_spot(config['paridade'], trades[0]['amount_enrolled'], trades[0]['instrument_dir'], 1) print(trades[0]) time.sleep(60) ok = True # Correcao de bug em relacao ao retorno de datas errado res = round(time.time() - datetime.timestamp(timestamp_converter(trades[0]['created_at'] / 1000, 2)), 2) ok = True if res <= int(config['filtro_diferenca_sinal']) else False if len(filtro_top_traders) > 0: if trades[0]['user_id'] not in filtro_top_traders: ok = False
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()))
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))
else: print('\n\nConectado com sucesso') break time.sleep(1) for sinal in lista: dados = sinal.split(',') data = dados[0] hora = dados[1] par = str(dados[2]) timeframe = int(dados[3]) direcao = dados[4] stake = float(dados[5]) agora = datetime.now() data_atual = agora.strftime('%d/%m/%Y') while data >= data_atual: entrou = 1 now = datetime.now() hora_atual = now.strftime("%H:%M:%S") direction = direcao.lower() if hora_atual == dados[1]: print('Operação realizada no par: ' + str(par) + ' ás ' + str(hora) + '. Timeframe: ' + str(timeframe) + ', Direção: ' + str(direcao) + ' Stake: ' + str(stake)) print('=+=+=+' * 20) _, id = (API.buy(stake, par, direcao, timeframe)) break if entrou == 0: print('Não foi possível executar a operação!')
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.gale = valor self.entrada = 'put' self.time = tempo self.account = conta self.pares = ['EURUSD-OTC', 'EURGBP-OTC', 'AUDCAD-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() self.Account() if self.API.connect(): 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(self.value, self.par, 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...') result = self.resultVerification(self.id_compra) if result > 0: self.winResult() elif result == 0: self.Compra() else: self.lossResult() # Retorna se bateu a meta def winResult(self): self.win += 1 self.gale = self.value self.loss = 0 if self.win == 2: return print("Goal hit ;D") self.par = self.pares[self.RandomNumber()] self.Compra() # Retorna se deu loss ou hit def lossResult(self): self.loss += 1 if self.loss == 3: return print("Hit :/") else: newValue = self.galeValue(self.gale) compra_status, self.id_compra = self.API.buy( newValue, self.par, self.entrada, self.time) newResult = self.resultVerification(self.id_compra) if newResult < 0: self.lossResult() elif newResult == 0: self.API.buy(newValue, self.par, self.entrada, self.time) else: newValue = self.value self.winResult() # Retorna o novo valor, fazendo o Maringale def galeValue(self, galeValue): galeValue = (galeValue * 1.15) * 2 self.gale = galeValue return galeValue # Verificar e retorna o valor do resultado da operação def resultVerification(self, id): return self.API.check_win_v3(self.id_compra)
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() res = Iq.get_balance() print(res) print(Iq.check_connect()) goal = "EURUSD" # # print("get candles") # # print(Iq.get_candles(goal,60,111,time.time())) Money = 1 ACTIVES = "EURUSD" ACTION = "call" #or "put" expirations_mode = 1 # check, id = Iq.buy(Money, ACTIVES, ACTION, expirations_mode) if check: print("!buy!") else: print("buy fail")
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
def sell_function(self): iq = IQ_Option("*****@*****.**", "FAKErayan106") iq.connect() print("Sell Process Connected") goal = "EURUSD-OTC" size = 120 maxdict = 30 money = 5 expirations_mode = 2 ACTION = "" # "call" or "put" iq.start_candles_stream(goal, size, maxdict) sell_macd_first_trigger = False sell_macd_second_trigger = False sell_macd_third_trigger = False sell_sma_trigger = False def get_stockstats_df(): # get real time candles from iqoptions candles = iq.get_realtime_candles(goal, size) data = [] # convert the dictionary of dictionaries from the candles into a list for i, k in candles.items(): data.append(k) # convert the list into a padas Dataframe df = pd.DataFrame(data=data) df.drop(labels=["id", "from", "at"], axis=1) # convert the pandas dataframe into a stockstats dataframe (still works with pandas) stock = StockDataFrame.retype(df) return stock while True: stock = get_stockstats_df() # enable macd, macds and macdh in the stockstats dataframe stock["macd"] # select the last row of the dataframe sell_macd_last_row = stock.tail(1) # get macd value from the stockstats dataframe macd = sell_macd_last_row.get("macd") macd = float(macd) macd = np.around(macd, decimals=5) # get macds value from the stockstats dataframe macds = sell_macd_last_row.get("macds") macds = float(macds) macds = np.around(macds, decimals=5) # check for macd first trigger if not sell_macd_first_trigger: if (macd > macds) and (abs(macd - macds) >= 0.00001): sell_macd_first_trigger = True print("sell macd first trigger activated") # check for macd second trigger if not sell_macd_second_trigger: if sell_macd_first_trigger and (macd == macds): sell_macd_second_trigger = True print("sell macd second trigger activated") # check for third trigger if not sell_macd_third_trigger: if sell_macd_second_trigger: duration = 180 end = time.time() + duration while time.time() < end: stock = get_stockstats_df() stock["macd"] # select the last row of the dataframe sell_macd_last_row = stock.tail(1) # get macd value from the stockstats dataframe macd = sell_macd_last_row.get("macd") macd = float(macd) macd = np.around(macd, decimals=5) # get macds value from the stockstats dataframe macds = sell_macd_last_row.get("macds") macds = float(macds) macds = np.around(macds, decimals=5) if (macd > macds) and (abs(macd - macds) >= 0.00001): sell_macd_third_trigger = True print("Sell macd third trigger activated") break if not sell_macd_third_trigger: sell_macd_first_trigger = False sell_macd_second_trigger = False print("Sell macd triggers reset") # check for sma trigger if not sell_sma_trigger: if sell_macd_third_trigger: print("sell check sma") # check for sma triggers for 8 minutes duration = 480 end = time.time() + duration while time.time() < end: stock = get_stockstats_df() stock["open_6_sma"] stock["open_14_sma"] sma_last_row = stock.tail(1) sma_6 = sma_last_row.get("open_6_sma") sma_6 = float(sma_6) sma_6 = np.around(sma_6, decimals=5) sma_14 = sma_last_row.get("open_14_sma") sma_14 = float(sma_14) sma_14 = np.around(sma_14, decimals=5) if not sell_sma_trigger: if sma_6 == sma_14: sell_sma_trigger = True print("sell sma trigger activated") break if not sell_sma_trigger: sell_macd_first_trigger = False sell_macd_second_trigger = False sell_macd_third_trigger = False print("Sell Macd triggers have been reseted") # check for buy or sell if sell_sma_trigger: print("checking if to sell") while True: stock = get_stockstats_df() stock["open_6_sma"] stock["open_14_sma"] sma_last_row = stock.tail(1) sma_6 = sma_last_row.get("open_6_sma") sma_6 = float(sma_6) sma_6 = np.around(sma_6, decimals=5) sma_14 = sma_last_row.get("open_14_sma") sma_14 = float(sma_14) sma_14 = np.around(sma_14, decimals=5) if (sma_6 < sma_14) and (abs(sma_6 - sma_14) >= 0.00001): ACTION = "put" iq.buy(money, goal, ACTION, expirations_mode) print("sell bid placed\n") sell_macd_first_trigger = False sell_macd_second_trigger = False sell_macd_third_trigger = False sell_sma_trigger = False break
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
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 par == tendencia or tendencia == "False": #status,id=API.buy_digital_spot(ACTIVES,Money,ACTION,expirations_mode) status, id = API.buy(Money, ACTIVES, ACTION, expirations_mode) print("operação realizada, Boa Sorte: ") if status: threading.Thread(target=teste, args=( id, lucro, Money, ACTIVES, ACTION, expirations_mode, martingale, contador, API, stop_loss,
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 API.check_win_v3(id) except: status = True valor = 0 if status: valor = valor if valor > 0 else float( '-' + str(abs(valor_entrada))) lucro += round(valor, 2)
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()
# Entradas na digital _, id = API.buy_digital_spot(par, entrada, direcao, timeframe) if isinstance(id, int): while True: status, lucro = API.check_win_digital_v2(id) if status: if lucro > 0: print('RESULTADO: WIN / LUCRO: ' + str(round(lucro, 2))) else: print('RESULTADO: LOSS / LUCRO: -' + str(entrada)) break # Entradas na binaria status, id = API.buy(entrada, par, direcao, timeframe) if status: resultado, lucro = API.check_win_v3(id) print('RESULTADO: ' + resultado + ' / LUCRO: ' + str(round(lucro, 2))) def configuracao(): arquivo = configparser.RawConfigParser() arquivo.read('config.txt') return { 'paridade': arquivo.get('GERAL', 'paridade'), 'valor_entrada': arquivo.get('GERAL', 'entrada'), 'timeframe': arquivo.get('GERAL', 'timeframe')
acerto = 0 erroCont = 0 erro = 0 doji = 0 par = pares[numberRandom] acertividade = 0 while True: #Informação da banca print("O par que esta sendo comprado: ", par) # Compra compra_status, id = API.buy(valor, par, entrada, tempo) print("Status da compra: ", compra_status, id) while compra_status == False: numberRandom = randint(0, 5) par = pares[numberRandom] compra_status, id = API.buy(valor, par, entrada, tempo) if compra_status == True: print("O par que esta sendo comprado: ", par) print("Status da compra: ", compra_status, id) break print("Aguardando resultado...") result = API.check_win_v3(id) if result > 0: