首页 > 解决方案 > Python 直接访问 Login 而不使用 With Function as Key :

问题描述

这是我尝试使用 ForexConnect().get_history(.... 而不是 fx.get_history( 并且我不希望这行代码“使用 ForexConnect() as fx:”的完整代码:”如何实现这一点,给出的最后一段代码会产生异常问题。

为什么我不想使用“with ForexConnect() as fx:” 原因是一旦会话“with ForexConnect() as fx:”该功能被注销。我的想法是在登录后进入会话。所以我不想用“with ForexConnect() as 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 部分结束,会话就会断开连接。

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)

要留在会话中,请尝试以下代码而不使用“With”和 as:

此处登录成功但无法获取history中的数据 = 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。和 as 的替代方法是什么:为什么当我尝试以 history = ForexConnect().get_history (...

标签: pythonpython-3.xsessionloginwith-statement

解决方案


推荐阅读