Python получает доступ к логину напрямую, не используя With Function as Key: - PullRequest
0 голосов
/ 23 ноября 2018

Вот полный код, где я пытаюсь использовать ForexConnect (). Get_history (.... вместо fx.get_history (и я не хочу эту строку кода "с ForexConnect () как fx:" какДля достижения этой цели в последнем разделе кода возникают проблемы с исключениями.

Почему я не хочу использовать "с ForexConnect () как fx:" Причина - однажды сеанс "с ForexConnect () как fx:"функция вышла из системы. Моя идея состоит в том, чтобы быть в сеансе после того, как вошел в систему. Так что я не хочу пробовать это с "с ForexConnect () как fx:"

import argparse

import pandas as pd
from forexconnect import ForexConnect, fxcorepy

import common_samples

parser = False


def parse_args():
    parser = argparse.ArgumentParser(description='Process command parameters.')
    common_samples.add_main_arguments(parser)
    common_samples.add_instrument_timeframe_arguments(parser)
    common_samples.add_date_arguments(parser)
    common_samples.add_max_bars_arguments(parser)
    args = parser.parse_args()
    return args


def main():
    if parser == False :
        #args = parse_args()
        str_user_id = 'Dxxxx'
        str_password = 'xxxxx'
        str_url = "http://www.fxcorporate.com/Hosts.jsp"
        str_connection = 'Demo'
        str_session_id = 'None'
        str_pin = 'None'
        str_instrument = 'USOil'
        str_timeframe = 'W1'
        quotes_count = 5
        date_from = None
        date_to = None
    else :
        args = parse_args()
        str_user_id = args.l
        str_password = args.p
        str_url = args.u
        str_connection = args.c
        str_session_id = args.session
        str_pin = args.pin
        str_instrument = args.i
        str_timeframe = args.timeframe
        quotes_count = args.quotescount
        date_from = args.datefrom
        date_to = args.dateto

    with ForexConnect() as fx:
        try:
            fx.login(str_user_id, str_password, str_url,
                     str_connection, str_session_id, str_pin,
                     common_samples.session_status_changed)

            print("")
            print("Requesting a price history...")
            print(str_instrument,str_timeframe,date_from,date_to,quotes_count)
            history = fx.get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)
            current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)

            date_format = '%d.%m.%Y %H:%M:%S'
            print("print history ",history)
            df = pd.DataFrame(history, columns=['Date', 'BidOpen', 'BidHigh','BidLow', 'BidClose', 'AskOpen', 'AskHigh', 'AskLow', 'AskClose', 'Volume'])
            print(df)
            if current_unit == fxcorepy.O2GTimeFrameUnit.TICK:
                print("Date, Bid, Ask")
                print(history.dtype.names)
                for row in history:
                    print("{0:s}, {1:,.5f}, {2:,.5f}".format(
                        pd.to_datetime(str(row['Date'])).strftime(date_format), row['Bid'], row['Ask']))
            else:
                print("Date, BidOpen, BidHigh, BidLow, BidClose, Volume")
                for row in history:
                    print("{0:s}, {1:,.5f}, {2:,.5f}, {3:,.5f}, {4:,.5f}, {5:d}".format(
                        pd.to_datetime(str(row['Date'])).strftime(date_format), row['BidOpen'], row['BidHigh'],
                        row['BidLow'], row['BidClose'], row['Volume']))
        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)


if __name__ == "__main__":
    main()
    print("")
    input("Done! Press enter key to exit\n")

Здесь я хочувойдите один раз и будьте в зарегистрированном сеансе навсегда. С помощью функции ниже это работает нормально. Но здесь проблема в том, что после того, как раздел «С» закончился, сеанс отключается.

with ForexConnect() as fx:
    try:
        fx.login(str_user_id, str_password, str_url,
                 str_connection, str_session_id, str_pin,
                 common_samples.session_status_changed)
        history = fx.get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)
            current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)

Чтобы остаться в сеансепопробовал приведенный ниже код без использования «С» и как:

Здесь вход выполнен успешно, но не удалось получить данные в истории = ForexConnect (). get_history

Код ошибки:

                ForexConnect().login(str_user_id, str_password, str_url,
                    str_connection, str_session_id, str_pin,
                    common_samples.session_status_changed)
               **history = ForexConnect().get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)**

Какчтобы код ** ** работал без ошибок, без использования With --- as: keyworkds.Какова альтернатива для этого и как: почему, когда я пытаюсь получить доступ как history = ForexConnect (). get_history (... это дает ошибку, как преодолеть эту проблему.

...