Exemple #1
0
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()
Exemple #2
0
    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)
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'])

    elif tipo == 'digital':

        API.subscribe_strike_list(par, timeframe)
        while True:
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'])
        valores['close'] = np.append(valores['open'], velas[x]['close'])
        valores['volume'] = np.append(valores['open'], velas[x]['volume'])
Exemple #5
0
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()
Exemple #6
0
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)
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
Exemple #8
0
#######################################################################################################################################

loggin()  #Loggin on iq Option
setMode('PRACTICE')  #Set practice mode
getBalance()  #Get account balance
print(CurrencyPair)  #Print pair to trade
setCoeficient()  #Define coeficient
startStream()  #Initialize stream to get realtime candles.

print('Bot is running and waiting for a row match...')

#######################################################################################################################################

while executeLoop:
    candle = api.get_realtime_candles(CurrencyPair,
                                      candleTime)  #get candles in realtime
    counter = 0  #Reset counter to 0 when starting the loop.
    time.sleep(0.025)  #Sleep 25ms to avoid getting bloqued.

    for candles in candle:  #loop trough candles to get values (Only 1 loop cause only one candle is asked.)
        candleId = candle[candles]['id']
        candleOpen = candle[candles]['open']
        candleClose = candle[candles]['close']
        candleFrom = candle[candles]['from']

    if candleOpen < candleClose:  #Define if candle is Verde, Roja, Empate
        d2 = {candleId: 'V'}
    elif candleOpen > candleClose:
        d2 = {candleId: 'R'}
    else:
        d2 = {candleId: 'E'}
from iqoptionapi.stable_api import IQ_Option
import time
from datetime import datetime

api = IQ_Option("email", "password")
api.connect()
print(api)
goal = "EURUSD"
size = 1
maxdict = 1

print("Start stream...")
api.start_candles_stream(goal, size, maxdict)
print("Print candles...")
candle = api.get_realtime_candles(goal, size)
key = list(candle)[0]
current_price = candle[key]['close']
print("Current price", current_price)

duration = 1
amount = 1
buy = "call"
#api.subscribe_strike_list(goal)
data = api.get_realtime_strike_list(goal, duration)
price_list = list(data.keys())
close_current_price = []
for p_list in price_list:
    close_current_price.append(abs(current_price - float(p_list)))
most_close_price = price_list[close_current_price.index(
    min(close_current_price))]
print("Most close price: {}\nCurrent price: {}".format(most_close_price,
Exemple #10
0
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)