我使用HTTParty连接到stockfighter.io的API并获取股票报价,然后我从中提取每股价格并将其附加到{{1数组。
我试图平均不断更新的数组$averageArr
的最后五个值,所以我想我会将变量$averageArr
设置为零,添加最后五个将值除以它,然后除以5得到动态变化的平均值。
这是我的代码:
sum
我第45行(已评论)遇到了问题,其中我收到有关require 'rubygems'
require 'httparty'
require 'json'
apikey = 'API_KEY_FOR_LOGIN_HERE'
venue = "VENUEX"
stock = "FOOBAR"
base_url = "https://api.stockfighter.io/ob/api"
account = "MY_ACCOUNT_HERE"
$averageArr = []
$counter = 0
$currAve = 0
def getQuote(stock, venue, account)
response = HTTParty.get("https://api.stockfighter.io/ob/api/venues/#{venue}/stocks/#{stock}/quote")
orderbook = response.parsed_response
puts orderbook["ok"]
return orderbook["last"]
puts orderbook["lastTrade"]
end
def getAverage(stock, venue, account)
$averageArr.push(getQuote(stock, venue, account))
$counter += 1
if $counter > 5
sum = 0
#line 43
for i in 1..5 do
# this one is line 45
sum += $averageArr[$averageArr.count - i]
end
return sum/5
$currAve = sum/5
else
return 'WAITING FOR QUOTE. CURRENT:'
end
end
# line 62
for i in 1..10 do
# line 64
getAverage(stock, venue, account)
if $counter > 5
if getQuote(stock, venue, account) < $currAve - 25 and numShares < 999
order = {
"account" => account,
"venue" => venue,
"symbol" => stock,
"price" => 1, #$250.00 -- probably ludicrously high
"qty" => 1,
"direction" => "buy",
"orderType" => "market" # See the order docs for what a limit order is
}
response = HTTParty.post("#{base_url}/venues/#{venue}/stocks/#{stock}/orders",
:body => JSON.dump(order),
:headers => {"X-Starfighter-Authorization" => apikey}
)
elsif getQuote(stock, venue, account) > $currAve + 25 and numShares > 0
order = {
"account" => account,
"venue" => venue,
"symbol" => stock,
"price" => 1, #$250.00 -- probably ludicrously high
"qty" => 1,
"direction" => "sell",
"orderType" => "market" # See the order docs for what a limit order is
}
response = HTTParty.post("#{base_url}/venues/#{venue}/stocks/#{stock}/orders",
:body => JSON.dump(order),
:headers => {"X-Starfighter-Authorization" => apikey}
)
end
end
end
和FixNum
的错误:
nil
我可能试图访问并索引数组上的范围,但这似乎不是问题所在。任何帮助将不胜感激。
答案 0 :(得分:0)
你的语法很好。问题是您的方法没有验证数据。
a += b
扩展为a = a + b
,这会在b
为nil
时引发您遇到的错误。
您需要确保getQuote
始终返回一个数字,或者在执行数学运算之前将任何您想要平均的数字转换为数字。
对于前者,您可以将return orderbook["last"]
更改为return orderbook["last"].to_f
对于后者,sum += $averageArr[$averageArr.count - i].to_f