Пример #1
0
def sign(email, password):
    error_password = """{"code":"invalid_credentials","message":"You entered the wrong credentials. Please check that the login/password is correct."}"""
    iqoption = IQ_Option(email, password)
    check, reason = iqoption.connect()
    MODE = 'PRACTICE'
    if check:
        print('\n')
        print("user " + email + " connected ")
        iqoption.change_balance(MODE)
        return iqoption

        #if see this you can close network for test
    elif iqoption.check_connect() == False:  #detect the websocket is close
        print("try reconnect")
        check, reason = iqoption.connect()
        if check:
            print("Reconnect successfully")
        else:
            if reason == error_password:
                print("Error Password")
            else:
                print("No Network")
    else:

        if reason == "[Errno -2] Name or service not known":
            print("No Network")
        elif reason == error_password:
            print("Error Password")
Пример #2
0
def apiConnect(email, password):
    API = IQ_Option(email, password)
    while_run_time = 10
    check, reason = API.connect()

    API.change_balance("PRACTICE")

    return API, while_run_time, check, reason
Пример #3
0
def login(verbose=False):

    if verbose:
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(message)s')

    iq = IQ_Option(USERNAME,
                   PASSWORD)  # YOU HAVE TO ADD YOUR USERNAME AND PASSWORD
    iq.change_balance("PRACTICE")  #or real
    return iq
Пример #4
0
 def get_connection(self):
     user = os.environ.get('IQOPTIONAPI_USER', None)
     password = os.environ.get('IQOPTIONAPI_PASS', None)
     if user:
         connection = IQ_Option(user, password)
         connection.connect()
         connection.change_balance(self.MODE)
         return connection
     else:
         sys.exit("Missing environment variables!")
Пример #5
0
def iqoption_connection():
    MODE = 'PRACTICE'  # TODO: Where to set PRACTICE / REAL?
    user = os.environ.get('IQOPTIONAPI_USER', None)
    password = os.environ.get('IQOPTIONAPI_PASS', None)
    if not user:
        sys.exit(
            "Missing environment variables IQOPTIONAPI_USER or IQOPTIONAPI_PASS !"
        )
    connection = IQ_Option(user, password)
    check, reason = connection.connect()
    if not check:
        raise Exception(reason)
    connection.change_balance(MODE)
    return connection
Пример #6
0
def entrar(editEmail, editSenha):
    #print(editSenha.get())
    API = IQ_Option(editEmail, editSenha)
    API.connect()
    API.change_balance("PRACTICE")
    #API.set_max_reconnect(5)

    while True:
        if API.check_connect() == False:
            print("Erro ao Conectar")
            API.reconnect()
        else:
            print("Conectado com sucesso!")
            tela_operacional(editEmail, editSenha)
            break
        time.sleep(5)
Пример #7
0
    def getConnection(self):
        API = IQ_Option('login', 'senha')

        check, reason = API.connect()
        API.change_balance('PRACTICE')  # PRACTICE / REAL

        while True:
            if API.check_connect() == False:
                print('Erro ao se conectar')
                API.connect()
            else:
                print('Conectado com sucesso')
                break

            time.sleep(1)
        return API
Пример #8
0
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'
Пример #9
0
def get_CandleResults(lista):
    returnedList = []
    init(autoreset=True)
    API = IQ_Option('*****@*****.**', 'Fh006131__')
    check, reason=API.connect()#connect to iqoption
    API.change_balance('PRACTICE')

    # while True:

    if API.check_connect() == False:
        print('Erro ao se conectar')
    else:
        for l in lista:
            l = l.split(',') 
            horario = datetime.strptime(l[0] + ":00", "%Y-%m-%dT%H:%M:%S")
            horario = datetime.timestamp(horario)
            if l[3] == "M5":
                velas = API.get_candles(l[1],300,3,int(horario))
            elif l[3] == "M15":
                velas = API.get_candles(l[1],900,3,int(horario))
            else:
                print ('Dado não lido. Incompatível!')    

            for v in range(len(velas)):
                if int(velas[v]['from']) == int(horario):
                    dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji'
                    if dir == l[2].lower():
                        returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅')
                        print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN')
                    else:
                        if int(velas[v]['from']) == int(horario):
                            dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji'
                            if dir == l[2].lower():
                                returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅1️⃣')
                                print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN')
                            else:
                                if int(velas[v]['from']) == int(horario):
                                    dir = 'call' if velas[v]['open'] < velas[v]['close'] else 'put' if velas[v]['open'] > velas[v]['close'] else 'doji'
                                    if dir == l[2].lower():
                                        returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-✅2️⃣')
                                        print(l[0],l[1],l[2],l[3],'|', Fore.GREEN + 'WIN')
                                    else:
                                        returnedList.append(l[0]+','+l[1]+','+l[2]+','+l[3]+'-❌')
                                        print(l[0],l[1],l[2],l[3],'|', Fore.RED + 'LOSS')                           
Пример #10
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)
Пример #11
0
def main():
    logs.print_message("Bot Started!")

    #login
    logs.print_message("Login Credentials IQ Option:")
    email = input("Email:")
    password = input("Pass:"******"Error on try to login. Check iq option credentials on environment variables.")
        exit()
    logs.print_message("Conected: IQ Option!")

    #stops
    #REAL / PRACTICE
    account_type = input("Set the account type (REAL or PRACTICE):")
    api.change_balance(account_type)
    original_balance = api.get_balance()
    logs.print_message("Original balance: $ {}".format(original_balance))
    stop_loss = input("Set a stop loss value:")
    stop_win = input("Set a stop win value:")

    #read trades
    f = open("trades.csv")
    csv_f = csv.reader(f)
    counter = 0
    for row in csv_f:
        if counter == 0:
            logs.print_message("Programming Orders...")
        else:
            start_time = datetime.datetime.strptime(row[1], '%H:%M')
            time_result = start_time - datetime.timedelta(seconds=15)
            add_option(row[0].replace('/', ''), time_result.strftime("%H:%M:%S"), row[2], row[3], stop_loss, stop_win, api, original_balance)
        counter = counter + 1

    logs.print_message("\nProcessing Orders...")

    while True:
        schedule.run_pending()
        time.sleep(1)
Пример #12
0
    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 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)
Пример #14
0
from iqoptionapi.stable_api import IQ_Option
import time, json
from datetime import datetime
from dateutil import tz

API = IQ_Option('login', 'senha')
API.connect()
API.change_balance('PRACTICE')

while True:
    if API.check_connect() == False:
        print('Erro ao se conectar')
        API.connect()
    else:
        print('Conectado com sucesso')
        break

    time.sleep(1)


def perfil():
    perfil = json.loads(json.dumps(API.get_profile_ansyc()))

    return perfil
    '''
		name
		first_name
		last_name
		email
		city
		nickname
Пример #15
0
from iqoptionapi.stable_api import IQ_Option
import time, json, logging, configparser
from datetime import datetime, date, timedelta
from dateutil import tz
import sys

logging.disable(level=(logging.DEBUG))

API = IQ_Option('login', 'senha')
API.connect()

API.change_balance('PRACTICE')  # PRACTICE / REAL

while True:
    if API.check_connect() == False:
        print('Erro ao se conectar')

        API.connect()
    else:
        print('\n\nConectado com sucesso!')
        break

    time.sleep(1)


def perfil():
    perfil = json.loads(json.dumps(API.get_profile_ansyc()))

    return perfil
    '''
		name
Пример #16
0
    print('Banca final:', str(banca()))
    print('Hora de início:', hora_inicio)
    print('Hora de término:', hora())


def printar_resumo():
    print('Tipo: ' + TIPO_PAR + ' / Par: ' + par)
    print(hora())


# ------------------- MAIN

system('cls')
print('\n\n\n\n')

api = IQ_Option(EMAIL, SENHA)
api.connect()
api.change_balance(TIPO_CONTA)

par = input('Par: ').upper()
stop_gain = round(float(input('Stop Gain: ')), 2)
qtd_win = int(input('Dividir o Stop Gain em quantos MHI?: '))

entrada_base = entrada_base_martingale()

hora_inicio = hora()
banca_inicio = banca()

iniciar_thread_checar_conexao()
iniciar_thread_atualizar_payout()
iniciar_mhi()
Пример #17
0
EMAIL = Credentials().email  # email de login
PASSWORD = Credentials().password  # senha da conta
CYCLE_DURATION = 15  # tempo de cada ciclo
EXPIRATION_TIME = 5  # tempo de expiração
ACTION = 'put'  # call/put
MINIMUN_PAYOUT = 74  # payout mínimo pra fazer a entrada
OPERATIONS = {}  # lista de operações do dia
ALL_ASSETS = []  # lista com todos os ativos
INITIAL_BALANCE = 0  # banca inicial

while True:
    try:
        print('Trying to connect...')
        API = IQ_Option(EMAIL, PASSWORD)
        API.set_max_reconnect(5)
        API.change_balance(ACCOUNT)
    except:
        print('Error defining API, trying again')
        continue
    break

while True:
    if API.check_connect() == False:
        print('Not connected')
        API.connect()
    else:
        print('Connected')
        break
    time.sleep(1)
results_file = open('results/results_{}.txt'.format(FILE_NAME), 'a+')
Пример #18
0
mode = 'PRACTICE'
# allow unlimited reconnect, (_) number of reconnection.
iq.set_max_reconnect(-1)
# Check connection.

while iq.check_connect() == False:  # detect the websocket is close
    print("try reconnect")
    iq.connect()  # try to connect
    print("reconnect Success")
    time.sleep(1)

# send status updated.
print("\n\n\tConnection Success.\n\n")
print('\nWorking in \"' + mode + ' MODE\"\n')
# check balance and change mode.
iq.change_balance(mode)
balance = float(str(iq.get_balance()))

currency_pair = {
    'EURUSD', 'USDJPY', 'GBPUSD', 'USDCHF', 'EURJPY', 'USDCAD', 'AUDUSD'
}

browser = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    user_agent=
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
)


def check_winrate(action):
    browser.open("https://binary-signal.com/en/chart/" + action)
Пример #19
0
import random
import time
import json
from iqoptionapi.stable_api import IQ_Option
from datetime import datetime

print("login...")
api = IQ_Option("*****@*****.**", "zoom3.m.2009")
api.change_balance("PRACTICE")
profits = api.get_all_profit()
print(profits)
Пример #20
0
# Video: https://www.youtube.com/watch?v=xp62AV8LWJk

import sys
import time

from iqoptionapi.stable_api import IQ_Option

API = IQ_Option("login", "senha")
API.connect()

API.change_balance("PRACTICE")  # PRACTICE / REAL

if API.check_connect():
    print(" Conectado com sucesso!")
else:
    print(" Erro ao conectar")
    input("\n\n Aperte enter para sair")
    sys.exit()

porcentagem_lucro = 10
entrada = 10.0
par = "EURUSD"
timeframe = 1
valor_minimo = round(float(entrada) * (float(porcentagem_lucro / 100)), 2)

API.subscribe_strike_list(par, timeframe)

status, id = API.buy_digital_spot(par, entrada, "put", timeframe)
time.sleep(2)

while API.get_async_order(id)["position-changed"]["msg"]["status"] == "open":
Пример #21
0
        if d != False:
            d = round(int(d) / 100, 2)
            break
        time.sleep(1)
    API.unsubscribe_strike_list(par, 1)

    return d


API = IQ_Option(email, senha)
API.connect()

# modo = raw_input(' PRACTICE / REAL ?? ')
modo = "PRACTICE"

API.change_balance(modo)  # PRACTICE / REAL

if API.check_connect():
    print(' Conectado com sucesso!')
else:
    print(' Erro ao conectar')
    input('\n\n Aperte enter para sair')
    sys.exit()

operacao = 2

par = raw_input(' Indique uma paridade para operar: ')
valor_entrada = float(input(' Indique um valor para entrar: '))
valor_entrada_b = float(valor_entrada)

martingale = 0
Пример #22
0
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
Пример #23
0
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")
Пример #24
0
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
Пример #25
0

def PrintarResumo():
    print('Tipo: ' + TIPO + ' / Par: ' + par)
    print(Hora())


def PrintLog(msg):
    print('\n')
    print('Log [' + str(msg) + ']: ' + Hora())


# ------------------- MAIN

system('cls')
print('\n\n\n\n')

api = IQ_Option(EMAIL, SENHA)
api.connect()
api.change_balance(BALANCE)

par = input('Par: ').upper()

entrada_base = float(input('Entrada base: '))

hora_inicio = Hora()
banca_inicio = Banca()

IniciarThreadChecarConexao()
#IniciarThreadAtualizarPayout()
IniciarMHI()
Пример #26
0
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
Пример #27
0
            time.sleep(1)
    except:
        print('ERRO AO REALIZAR ENTRADA!!')
        time.sleep(1)

    if status:
        print(
            f'\n INICIANDO OPERAÇÃO {str(id)}..\n {str(horario)} | {par} | OPÇÃO: {opcao.upper()} | DIREÇÃO: {direcao.upper()} | M{timeframe} | PAYOUT: {payout}%\n\n'
        )
        Mensagem(
            f'INICIANDO OPERAÇÃO {str(id)}..\n {str(horario)} | {par} | OPÇÃO: {opcao.upper()} | DIREÇÃO: {direcao.upper()} | M{timeframe} | PAYOUT: {payout}%'
        )


API.connect()
API.change_balance(config['conta'])
while True:
    if API.check_connect() == False:
        print('>> Erro ao se conectar!\n')
        input('   Aperte enter para sair')
        sys.exit()
    else:
        print(
            f'>> Conectado com sucesso!\n {Fore.RED}VENDA DO BOT PROIBIDA!!!\n'
        )
        banca()
        config['banca_inicial'] = valor_da_banca
        print(
            f"{Fore.LIGHTBLUE_EX}Saldo da conta {'demo' if account_type == 'PRACTICE' else 'real'}: {account_balance}"
        )
        break
Пример #28
0
import telethon
from pyquery import PyQuery as pq
from iqoptionapi.stable_api import IQ_Option
import json

# import sys
json.load
api_id = 00000  #telegram bot api_id
api_hash = ''  #telegram bot api_hash
client = telethon.TelegramClient('name_of_session', api_id, api_hash)
amount = 100
use_trail_stop = False
auto_margin_call = False
use_token_for_commission = True
I_want_money = IQ_Option("", "")  #login,pass in IQoption
I_want_money.change_balance("PRACTICE")
with open("data_name_to_id.json", "r") as read_file:
    data_name_to_id = json.load(read_file)

with open("data_id_to_name.json", "r") as read_file:
    data_id_to_name = json.load(read_file)


def buy(mass):
    global I_want_money
    return I_want_money.buy_order(mass[0], mass[1], mass[2], mass[3], mass[4],
                                  mass[5], mass[6], mass[7], mass[8], mass[9],
                                  mass[10], mass[11], mass[12], mass[13],
                                  mass[14])

Пример #29
0
class IQ:
    def __init__(self):
        self.api = IQ_Option(os.environ["IQU"], os.environ["IQP"])
        self.api.connect()
        self.api.change_balance(ARG_BALANCE)
        self.currency = ARG_CURRENCY

        while True:
            if self.api.check_connect() == False:
                print('Erro ao conectar')
                self.api.connect
            else:
                print('Conectado com Sucesso')
                break
            time.sleep(3)

    def getCurrency(self):
        return self.currency

    def getBalance(self):
        return self.api.get_balance()

    def getEnterValue(self):
        banca = self.getBalance()
        bancaFloor = math.floor(banca / 40)
        return bancaFloor if int(banca) > 40 else 2.0
        # Limited to $USD 2

    def getServerDatetime(self):
        serverTime = self.api.get_server_timestamp()
        hora = datetime.strptime(
            datetime.utcfromtimestamp(serverTime).strftime(
                '%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        return hora.replace(tzinfo=tz.gettz('GMT'))

    def getCandles(self, rangeTime=60, quant=10):
        return self.api.get_candles(self.currency, rangeTime, quant,
                                    self.api.get_server_timestamp())

    def buyDigital(self, direction):
        return self.api.buy_digital_spot(self.currency, self.getEnterValue(),
                                         direction, ARG_DURATION)

    def checkResult(self, id):
        return self.api.check_win_digital_v2(id)

    def shouldEntry(self):
        serverTime = self.getServerDatetime()
        # minutes = float(serverTime.strftime('%M.%S')[1:])
        # return True if (minutes >= 4.58 and minutes <= 5) or minutes >= 9.58 else False
        seconds = int(serverTime.strftime('%S'))

        if seconds < 20:
            time.sleep(20)
        elif seconds < 30:
            time.sleep(10)

        goTrade = True if (seconds >= 48
                           and seconds <= 50) or seconds >= 58 else False
        if goTrade == False:
            time.sleep(1)

        return goTrade
Пример #30
0
print('Login info')
ID = input('Account: ')
PW = input('Password: '******'Run times: ')
Max_bet_amount_limit_set = input('Max bet limits: ')

print('login..')

I_want_money = IQ_Option(ID + "@gmail.com", PW)
#connect to iqoption
I_want_money.connect()
start_time_results = datetime.fromtimestamp(I_want_money.get_server_timestamp() + 3600 * 8)


I_want_money.change_balance('REAL')

start_balance_results = I_want_money.get_balance()
print(start_balance_results)
# get_all_open_time for choice array
ALL_Asset = dict
d = dict





def run(choice_market):
    I_want_money = IQ_Option(ID + "@gmail.com", PW)
    I_want_money.connect()
    # I_want_money.change_balance('PRACTICE')