从 python 变量中提取值

Extracting a value from python variable

当我 运行 以下代码时,我得到一个包含我想在代码中使用的值 (1.11113) 的输出(在第一部分之后)。我得到的完整输出显示在代码之后。基本上我想做的是提取实时外汇(股票)价值以用于订单。此订单将放置在同一 python 模块中的此初始代码之后。感谢您的帮助。

import json
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20
import oandapyV20.endpoints.pricing as pricing
from exampleauth import exampleAuth
import argparse
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import oandapyV20.endpoints.instruments as instruments
from oandapyV20.definitions.instruments import CandlestickGranularity
import re
import oandapyV20.endpoints.pricing as pricing

# pricef=float(price)
# parser.add_argument('--price', choices=price, default='M', help='Mid/Bid/Ask')
accountID, access_token = exampleAuth()
api = oandapyV20.API(access_token=access_token)

params = {"instruments": "EUR_USD"}
r = pricing.PricingInfo(accountID=accountID, params=params)
rv = api.request(r)

print(rv)

输出

{'prices': [{'asks': [{'liquidity': 10000000, 'price': '1.11132'}],
             'bids': [{'liquidity': 10000000, 'price': '1.11113'}],
             'closeoutAsk': '1.11132',
             'closeoutBid': '1.11113',
             'instrument': 'EUR_USD',
             'quoteHomeConversionFactors': {'negativeUnits': '1.00000000',
                                            'positiveUnits': '1.00000000'},
             'status': 'tradeable',
             'time': '2020-05-31T23:02:34.271983628Z',
             'tradeable': True,
             'type': 'PRICE',
             'unitsAvailable': {'default': {'long': '3852555',
                                            'short': '3852555'},
                                'openOnly': {'long': '3852555',
                                             'short': '3852555'},
                                'reduceFirst': {'long': '3852555',
                                                'short': '3852555'},
                                'reduceOnly': {'long': '0', 'short': '0'}}}],
 'time': '2020-05-31T23:02:40.672716661Z'}

看起来像你想要的:

rv['prices'][0]['bids'][0]['price']

至少对于这种情况。您可能并不总是想要第一个价格条目或第一个出价条目,在这种情况下,您可能希望根据要使用的任何标准进行某种排序或过滤,以便从多个条目中选择正确的条目。

您的输出是一个包含许多嵌套列表和字典的字典。

要访问字典中的值,使用与访问列表成员相同的语法,只是键不必是数字,可以是任何数据类型,通常是字符串。所以 rv['time'] 在你的情况下会产生 '2020-05-31T23:02:40.672716661Z'.

由于数字 1.11113 在字典中出现了两次,这里有两个指针可以访问相应的字段:

rv['prices'][0]['bids'][0]['price']

rv['prices'][0]['closeoutBid']

这将是字符串格式,因此要将其用作数字,您必须使用 float()

进行转换

还要注意偶尔 [0] 访问列表的第一个元素。