Python 显示嵌套在循环中并在动态列表上迭代的更新值
我目前正在编写一个小型python程序,在1Broker.com上使用API查看我当前的交易,它应该列出所有未平仓,使用计数器对其进行编号,然后在每次运行时在睡眠计时器后更新所选的统计数据(p/L百分比和仓位id) 我在一个肮脏的早期草案中工作,但是决定“优化”并清理我的代码。。。把它弄坏了。 下面是错误部分的一个片段:Python 显示嵌套在循环中并在动态列表上迭代的更新值,python,loops,dynamic,nested,Python,Loops,Dynamic,Nested,我目前正在编写一个小型python程序,在1Broker.com上使用API查看我当前的交易,它应该列出所有未平仓,使用计数器对其进行编号,然后在每次运行时在睡眠计时器后更新所选的统计数据(p/L百分比和仓位id) 我在一个肮脏的早期草案中工作,但是决定“优化”并清理我的代码。。。把它弄坏了。 下面是错误部分的一个片段: if self.total_open_positions != []: counter = int("0") for position in s
if self.total_open_positions != []:
counter = int("0")
for position in self.total_open_positions:
counter += 1
display = {}
display["Open Order"] = str(counter)
display["ID"] = str(position["position_id"])
display["P/L Percent"] = str(position["profit_loss_percent"])
print display
time.sleep(timer - ((time.time() - starttime) % timer))
if self.total_positions == []:
print "All trades closed"
在每个循环中,p/L百分比和ID中的数据拒绝更新
提前向任何提供帮助的人表示感谢:)
我所说的“拒绝更新”是指当程序运行时,它根据需要检索P/L百分比。但是,每个连续循环打印相同的P/L百分比。这意味着str(头寸[“损益百分比])的价值尚未更新为从网站检索到的最新数据。(例如,当交易额达到6%时,显示为3%)
左图为第一稿。然而,您可以看到,P/L%在每次迭代中都会发生变化。而在右图中,它保持不变
至于self.total_open_位置,它等于我的api请求:
self.total\u open\u positions=requests.get(API\u URL)
这里有一个“肮脏”版本的片段,至少可以正常工作,也许它可以帮助显示我的意图和我的noob水平技能(这就是为什么我需要帮助lol):
问题已经解决了。因为self.total_open_positions是在上面的函数中定义的,所以它只被调用一次,因此只得到一组统计数据。通过在我的循环范围内重新定义总打开位置,所有数据都会正确显示:)拒绝更新是什么意思?您是否可以显示一个示例输出以及您期望的结果。如果self.total\u open\u positions!您真的不需要
[]:
在for循环之前。还有任何不执行counter=0
vsint(“0”)
的原因,因为请求的数据是json对象,如果没有未平仓交易,则响应=[None]。这会导致任何获取ID和P/L的尝试出错,因为此时它们不存在,但如果是空列表,则for
循环将永远不会进入。这就是为什么我会认为空列表的测试是多余的。int(“0”)
太搞笑了!
total_open_orders = open_orders["response"]
while total_open_orders == []:
print "Checking again......"
time.sleep(timer1 - ((time.time() - starttime) % timer1))
else:
#When orders are found, loop through and display
while True:
#Wait desired time between refreshing stats
time.sleep(timer1 - ((time.time() - starttime) % timer1))
#Position number (oldest first)
counter = 0
##Print a small seperator between refreshes
print "#" * 20
#Loop through list of positions and print stats for each
for order in total_open_orders:
#Add to counter for each position
counter += 1
#Display stats to user (anything in '[]' is JSON format
try:
print "#" * 40
print "Open Order #: " + str(counter)
print "ID #: " + str(order["position_id"])
print "Market: " + str(order["symbol"])
print "Entry: " + str(order["entry_price"])
print "Stop Loss: " + str(order["stop_loss"])
print "Take Profit: " + str(order["take_profit"])
print "P/L: " + str(order["profit_loss_percent"])
print "#" * 40
print ""
#Catch any connection errors and print for debugging
except Exception as e:
print e