def main(): if not path.exists("iqdataset.csv"): with open("iqdataset.csv", 'w') as esc: esc.write("timestamp;varkandle\n") esc.close() else: pass iq = IQ_Option("","") # Login do user iq.set_max_reconnect(-1) if iq.check_connect(): while True: time.sleep(15) #Tempo para coletar, e sim, isso causa no resultado influência! try: goal = "EURUSD" # ATIVO size = 1 maxdict = 10 iq.start_candles_stream(goal, size, maxdict) cc = iq.get_realtime_candles(goal, 1) pp = pprint.PrettyPrinter(depth = 8) inti = cc tim = time.time() end_time = int(tim) - 0.8 end_cap = inti[int(end_time)]["min"] with open("iqdataset.csv", "a") as file: file = file.write(f"{end_time};{end_cap}\n") print(file) except Exception as e: print("ERRO:", e) continue if not iq.check_connect(): iq.connect() main()
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)
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 for velas in total: print(timestamp_converter(velas['from'])) # Pegar velas em tempo real ######################### par = 'EURUSD' API.start_candles_stream(par, 60, 1) time.sleep(1) while True: vela = API.get_realtime_candles(par, 60) for velas in vela: print(vela[velas]['close']) time.sleep(1) API.stop_candles_stream(par, 60) def payout(par, tipo, timeframe=1): if tipo == 'turbo': a = API.get_all_profit() return int(100 * a[par]['turbo'])
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' periodo = 14 tempo_segundos = 60 API.start_candles_stream(par, tempo_segundos, 280) while True: velas = API.get_realtime_candles(par, tempo_segundos) valores = { 'open': np.array([]), 'high': np.array([]), 'low': np.array([]), 'close': np.array([]), 'volume': np.array([]) } for x in velas: valores['open'] = np.append(valores['open'], velas[x]['open']) valores['high'] = np.append(valores['open'], velas[x]['max']) valores['low'] = np.append(valores['open'], velas[x]['min'])
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()
def run_bbot(email, pwd, active, expiration_time=5, money=2, bb_std=2.1, bb_window=20, ema_window=100, acc_type='PRACTICE', bot_token=None, bot_chatID=None): primes = [17, 19, 23, 29, 31, 37, 41, 43, 47] # Connect to IQOption iqoapi = IQ_Option(email, pwd) iqoapi.connect() iqoapi.change_balance(acc_type) # Check if pair is active and get their payout mpm = most_profit_mode(iqoapi, active, expiration_time, 0.70) update_time = random.choice(primes[1:]) if mpm[0] in ('turbo', 'digital') else 17 print("BBot [Active: {} Expiration: {} Type: {} Bet: {} Mode: {} UT: {}]". format(active, expiration_time, acc_type, money, mpm[0], update_time)) t_mpm = Timer(remaining_seconds(update_time), lambda: None) t_mpm.start() # Define the number of digits of price and indicators max_dict = 101 size = expiration_time * 60 #Get total of digits used by iq iqoapi.start_candles_stream(active, size, max_dict) candles = iqoapi.get_realtime_candles(active, size) frac, n = math.modf(candles[max(candles.keys())]['close']) nd = 7 - len(str(int(n))) ndi = 6 - len(str(int(n))) # Initialize several variables #order = [False] back_to_bb = True timer_trade = None # Initialize our infinite loop :D while True: # Check pair's status and its payout if not t_mpm.is_alive(): old_status = mpm[0] mpm = most_profit_mode(iqoapi, active, expiration_time, 0.70) if mpm[0] != old_status: if mpm[0] in ('payout', 'error', 'closed'): update_time = 17 print(" --- --- --- ") print(str(datetime.now()), active, "- Something went wrong - Reason:", mpm[0]) print(" --- --- --- ") else: update_time = random.choice(primes[1:]) print(" --- --- --- ") print(str(datetime.now()), active, "- is open now! Trading in", mpm[0]) print(" --- --- --- ") t_mpm = Timer(remaining_seconds(update_time), lambda: None) # Restart t_mpm.start() if mpm[1] and (not timer_trade or not timer_trade.is_alive()): candles = iqoapi.get_realtime_candles(active, size) df_time = pd.DataFrame( [(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'), candles[ts]["close"], candles[ts]["max"], candles[ts]["min"]) for ts in sorted(candles.keys(), reverse=True)], columns=['from', 'close', 'max', 'min']).set_index('from') df_time = df_time.sort_index(ascending=False) df_time_close = df_time['close'] #df_time_max = df_time['max'] #df_time_min = df_time['min'] curr_ema = ema(df_time_close.iloc[0:100], ema_window) # pegando valor corrente + 99 bbands = bollinger_bands(df_time_close.iloc[0:20], bb_window, bb_std) bb_hi = round(bbands.iloc[-1]['upper'], ndi) bb_lw = round(bbands.iloc[-1]['lower'], ndi) curr_price = df_time_close.iloc[0] #avg_max = np.mean(df_time_max[0:13]) #avg_min = np.mean(df_time_min[0:13]) if not back_to_bb and not timer_trade.is_alive(): if bb_hi < curr_price < bb_lw: back_to_bb = True #print(bb_hi, curr_price, bb_lw) #clear_output(wait=True) if back_to_bb and (not timer_trade or not timer_trade.is_alive()): if curr_price > bb_hi and curr_ema > bb_hi: signal = 'put' if mpm[0] == 'turbo': threading.Thread(target=buy_turbo, args=(iqoapi, active, money, signal, get_expiration_time())).start() elif mpm[0] == 'digital': threading.Thread(target=buy_digital, args=(iqoapi, active, money, signal, expiration_time)).start() back_to_bb = False timer_trade = Timer(remaining_seconds(), lambda: None) timer_trade.start() text = "IQBBot2.2 Ativo: {} - {}\nTaxa: {}\nSinal: {}\nHorário: {}\nExpiração: {}".format( active, mpm[0], curr_price, signal, datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), expiration_time) if bot_token is not None and bot_chatID is not None: telegram_bot_sendtext(bot_token, bot_chatID, text) print(text) elif curr_price < bb_lw and curr_ema < bb_lw: signal = 'call' if mpm[0] == 'turbo': threading.Thread(target=buy_turbo, args=(iqoapi, active, money, signal, get_expiration_time())).start() elif mpm[0] == 'digital': threading.Thread(target=buy_digital, args=(iqoapi, active, money, signal, expiration_time)).start() back_to_bb = False timer_trade = Timer(remaining_seconds(), lambda: None) timer_trade.start() text = "IQBBot2.2 Ativo: {} - {}\nTaxa: {}\nSinal: {}\nHorário: {}\nExpiração: {}".format( active, mpm[0], curr_price, signal, datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), expiration_time) if bot_token is not None and bot_chatID is not None: telegram_bot_sendtext(bot_token, bot_chatID, text) print(text) time.sleep(.1) #break iqoapi.stop_candles_stream(active, size)
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
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()))) candles = list(candles.values()) print(candles[0]) d = [[r(c['open']), r(c['close']), r(c['min']), r(c['max'])] for c in candles] for idx, dd in enumerate(d): print(dd) if idx == 10: break
class Start: def __init__(self): self.api = IQ_Option(config.USERNAME, config.PASSWORD) self.dispacher = Dispacher(self.api.api) self.api.change_balance(config.MODE) self.timesync = TimeSync(self.api, self.dispacher) self.bots = [] self.actives = [] self.generate_actives() self.create_bots() while True: if self.timesync.is_desconected(): self.stop_bots() print('disconnected trying to reconnect in {} seconds'.format(config.TIME_RECONNECT)) time.sleep(config.TIME_RECONNECT) if(self.reconnect()): print('successfully reconnected') self.create_bots() time.sleep(.3) def stop_bots(self): for bot in self.bots: if bot: bot.stop() def create_bots(self): self.bots = [] actives = self.get_operable_actives() for index, active in enumerate(actives): if index >= config.MAX_BOTS: break self.api.start_candles_stream(active.name, config.CANDLE_SIZE, config.MAX_CANDLES) bot = Bot(self, self.api, self.dispacher, self.timesync, active) self.bots.append(bot) bot.start() def get_balance(self): while True: try: respon = self.api.get_profile() if(respon["isSuccessful"] == True): return respon["result"]["balance"] except: self.reconnect() time.sleep(.5) def get_operable_actives(self) -> list: f = lambda active : active.enabled and active.is_profitable() return list(filter(f, self.actives)) def refresh_actives(self): if time.time() > self.last_refresh_actives + 60: self.last_refresh_actives = time.time() check, init_info = self.get_all_init() if check: actives = init_info['turbo']['actives'] for active in self.actives: active.set_data(actives[str(active.code)]) self.sort_actives() def generate_actives(self): self.last_refresh_actives = time.time() init_info: dict = self.api.get_all_init().get('result') actives = init_info['turbo']['actives'] self.actives = list(map(lambda code: Active(actives[code]), actives)) self.sort_actives() def sort_actives(self): self.actives = sorted(self.actives, key=attrgetter('profit'), reverse=True) def reconnect(self): try: self.api.api.close() result = self.api.api.connect() self.api.api.websocket.on_message = self.dispacher.on_message return result except: print('fail to reconnect') def start_candles_stream(self, ACTIVE, size, maxdict): if size in self.api.size: self.api.api.real_time_candles_maxdict_table[ACTIVE][size] = maxdict self.api.full_realtime_get_candle(ACTIVE,size,maxdict) self.api.start_candles_one_stream(ACTIVE,size) else: logging.error('**error** start_candles_stream please input right size') def get_all_init(self): self.api.api.api_option_init_all_result = None try: self.api.api.get_api_option_init_all() except: return False, None start = time.time() while True: if time.time() - start > 30 or self.api.api.api_option_init_all_result != None: break try: if self.api.api.api_option_init_all_result['isSuccessful']: return True, self.api.api.api_option_init_all_result['result'] except: return False, None
from iqoptionapi.stable_api import IQ_Option import numpy as np from multiprocessing import Process import pandas as pd from stockstats import StockDataFrame iq = IQ_Option("*****@*****.**", "FAKErayan106") iq.connect() asset = "EURUSD-OTC" size = 120 maxdict = 30 money = 5 expiration_mode = 2 iq.start_candles_stream(asset, size, maxdict) def get_stockstats_df(asset, size): #get real time candles from iqoptions candles = iq.get_realtime_candles(asset, 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)
from iqoptionapi.stable_api import IQ_Option import logging import time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') api = IQ_Option("*****@*****.**", "zoom3.m.2009") api.start_candles_stream("EURUSD-OTC", 15, 100) candles: list = api.get_realtime_candles("EURUSD-OTC", 100) print(candles) api.start_candles_stream("GBPUSD-OTC", 15, 100) candles: list = api.get_realtime_candles("GBPUSD-OTC", 100) print(candles)