Exemplo n.º 1
0
    def login(self):
        try:

            self.openUrl(config.URL, title_display="<Etoro>")

            if self.already_loggedin:
                logger.info(f'Already Logged as User:"******".')
                return True

            logger.info(f'Attempting Login as User:"******".')
            driver_status = self.get_status_of_driver()

            if driver_status == "Dead":
                logger.error("Cannot Login ([Error:: '<Driver Not Alive>'")
                return False
            # logger.info('Driver getting url: {}'.format(config.URL))

            self.do_login_request()

            login_status = self.get_loggedin_username()

            if login_status:
                logger.info("Login Successful: '{}'".format(login_status))
                return True
            else:
                return False
        except Exception as e:
            logger.error("Cannot Login ([Error:: '<{}>'])".format(str(e)))
            return False
Exemplo n.º 2
0
def set_data(data, path):
    try:
        with open(path, 'w') as fd:
            fd.write(json.dumps(data, indent=2))
    except TypeError:
        logging.error('Type error')
        set_data({}, path)
    except json.JSONDecodeError:
        logging.error('Json decode error')
Exemplo n.º 3
0
def buy_trade(etoro_instance):
    try:
        detail = ""

        # etoro_instance.login()
        #checking  current balance
        clientCredit = helpers.clientCredit(
            login_data=etoro_instance.get_login_info)

        open_markets_only = config.analyze_open_markets_only
        logger.info(
            f"Analyzing Today Stocks For {'opened' if open_markets_only else 'all'} markets ..."
        )

        analyzer = AnalyzeStocks()

        top_markets = analyzer.today_price_analysis(
            stocks_sort_by=config.stocks_sort_by,
            time_slots_count=24,
            open_markets_only=open_markets_only,
            time_slots_pick=2)

        # top_markets = analyzer.trade_insights(
        # 	etoro_instance.get_insights(),
        #  	open_markets_only=open_markets_only, sort_by="growth")

        for t1, top_market in enumerate(top_markets):
            logger.info(f"\nGoing to open Buying Trade for :\n{top_market}\n")
            buy_trade, buy_trade_res = etoro_instance.trade(
                ins=top_market.get("InstrumentId"), IsBuy=True)
            if buy_trade is False:
                detail = (
                    f"Couldnot open buying position for: '{top_market.get('SymbolFull')}'"
                    f" reason :\n{buy_trade_res}\n")
                logger.warning(detail)
            else:
                detail = (
                    f"Opened buying position for: '{top_market.get('SymbolFull')}'"
                    f" response :\n{buy_trade_res}\n")
                logger.info(detail)
                break

        logger.info(f"\nGoing to update User Date ...")
        user_data = etoro_instance.get_login_info
        logger.info(f"\nGot User Data :\n{user_data}\n")

        logger.info(f"\nGoing to update User Trade History ...")
        user_trade_history = etoro_instance.get_trade_history
        logger.info(f"\nGot User Trade History :\n{user_trade_history}\n")

        msg = '<buy_trade> finished ...'
        print('+' * len(msg))
        print(msg)
        print('+' * len(msg))

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        err_detail = e, fname, exc_tb.tb_lineno
        detail = f"Following Error occured in buy_trade ::\n{err_detail}\n"
        logger.error(detail)

    #write trade logs
    helpers.write_csv("Buying", detail)
Exemplo n.º 4
0
def sell_trade(etoro_instance):
    try:
        detail = ""
        # etoro_instance.login()

        logger.info(
            f"Going to get last Ordered Trades (For Opening Selling Position ) ..."
        )

        lastOrderedTrades = helpers.lastOrderedTrade(isBuy=True)

        if not lastOrderedTrades:
            logger.info(
                f"No Last Ordered Trades found to open a selling position.")

        for t1, lastOrderedTrade in enumerate(lastOrderedTrades):

            instrumentID = lastOrderedTrade['InstrumentID']
            instrumentData = helpers.find_instrument_by_id(instrumentID)
            lastOrderedTrade.update({
                k: v
                for k, v in instrumentData.items() if k in (
                    "InstrumentDisplayName",
                    "SymbolFull",
                )
            })
            instrumentSymbol = instrumentData["SymbolFull"]
            instrumentDisplayName = instrumentData["InstrumentDisplayName"]
            instrumentTitle = f"{instrumentSymbol} - {instrumentDisplayName}"
            positionID = lastOrderedTrade['PositionID']

            logger.info(
                f"\n[{t1+1}/{len(lastOrderedTrades)}] :\n{lastOrderedTrade}\n")

            logger.info(f"Going to get User Trade History ...")
            tradeHistory = etoro_instance.get_trade_history

            closedOrder = helpers.isOrderClosed(
                positionID,
                data_list=tradeHistory,
                path=config.closed_trade_history_file)

            if not closedOrder:
                logger.info(f"<[{instrumentTitle}]: postionID->"
                            f"{positionID} instrumentID->{instrumentID}>"
                            " is not closed yet. skipping this...")
                continue

            # here opens a selling postion for this trade

            logger.info(
                f"Going to open Selling Trade for: {instrumentTitle}\n")
            sell_trade, sell_trade_res = etoro_instance.trade(ins=instrumentID,
                                                              IsBuy=False)

            if sell_trade is False:
                detail = (
                    f"Couldnot open selling position for: '{instrumentTitle}'"
                    f" reason :\n{sell_trade_res}\n")
                logger.warning(detail)
            else:
                detail = (f"Opened selling position for: '{instrumentTitle}'"
                          f" response :\n{sell_trade_res}\n")
                logger.info(detail)

            logger.info(f"\nGoing to update User Date ...")
            user_data = etoro_instance.get_login_info
            logger.info(f"\nGot User Data :\n{user_data}\n")

            logger.info(f"\nGoing to update User Trade History ...")
            user_trade_history = etoro_instance.get_trade_history
            logger.info(f"\nGot User Trade History :\n{user_trade_history}\n")

        msg = "<sell_trade> finished ..."
        print('+' * len(msg))
        print(msg)
        print('+' * len(msg))

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        err_detail = e, fname, exc_tb.tb_lineno
        detail = f"Following Error occured in sell_trade ::\n{err_detail}\n"
        logger.error(detail)

    #write trade logs
    helpers.write_csv("Selling", detail)