Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions lib/alpaca/trade/api/bar.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
# frozen_string_literal: true

# object
# OHLC aggregate of all the trades in a given interval.

# t date-time required Timestamp in RFC-3339 format with nanosecond precision
# o double required Opening price
# h double required High price
# l double required Low price
# c double required Closing price
# v int64 required Bar volume
# n int64 required Trade count in the bar
# vw double required Volume weighted average price
module Alpaca
module Trade
module Api
class Bar
attr_reader :time, :open, :high, :low, :close, :volume
attr_reader :time, :open, :high, :low, :close, :volume, :trades, :weighted_average_price

def initialize(json)
@time = Time.at(json['t'])
@time = Time.parse(json['t'])
@open = BigDecimal(json['o'].to_s)
@high = BigDecimal(json['h'].to_s)
@low = BigDecimal(json['l'].to_s)
@close = BigDecimal(json['c'].to_s)
@weighted_average_price = BigDecimal(json['vw'].to_s)
@volume = json['v']
@trades = json['n']
end
end
end
Expand Down
55 changes: 48 additions & 7 deletions lib/alpaca/trade/api/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,49 @@ def assets(status: nil, asset_class: nil)
json.map { |item| Asset.new(item) }
end

def bars(timeframe, symbols, limit: 100)
# {
# "bars": {
# "AAPL": [
# {
# "t": "2022-01-03T09:00:00Z",
# "o": 178.26,
# "h": 178.26,
# "l": 178.21,
# "c": 178.21,
# "v": 1118,
# "n": 65,
# "vw": 178.235733
# }
# ]
# },
# "next_page_token": "QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg=="
# }
def bars(timeframe: '1D', symbols:, limit: 100, start_date: nil, end_date: nil, feed: 'sip', asof: nil)
validate_timeframe(timeframe)
response = get_request(data_endpoint, "v1/bars/#{timeframe}", symbols: symbols.join(','), limit: limit)
validate_symbols(symbols)

symbols = Array(symbols)
params = {
symbols: symbols.join(','),
limit: limit,
timeframe: timeframe,
feed: feed
}
params[:start] = start_date.rfc3339 if start_date
params[:end] = end_date.rfc3339 if end_date

params[:asof] = asof.strftime("%Y-%m-%d") if asof.is_a?(Date) || asof.is_a?(Time)
params[:asof] ||= asof if asof.is_a?(String)

response = get_request(data_endpoint, "v2/stocks/bars", params)
raise InvalidRequest, JSON.parse(response.body)['message'] if response.status == 404

json = JSON.parse(response.body)
json.keys.each_with_object({}) do |symbol, hash|
hash[symbol] = json[symbol].map { |bar| Bar.new(bar) }
hash = { "next_page_token" => json["next_page_token"], "bars" => {} }
symbols.each do |symbol|
hash["bars"][symbol] = json["bars"][symbol]&.map { |bar| Bar.new(bar) } || []
end
hash.merge({ 'next_page_token' => json['next_page_token'] })
end

def calendar(start_date: Date.today, end_date: (Date.today + 30))
Expand Down Expand Up @@ -249,9 +285,14 @@ def possibly_raise_exception(response)
end

def validate_timeframe(timeframe)
unless TIMEFRAMES.include?(timeframe)
raise ArgumentError, "Invalid timeframe: #{timeframe}. Valid arguments are: #{TIMEFRAMES}"
end
return if TIMEFRAMES.include?(timeframe)
raise ArgumentError, "Invalid timeframe: #{timeframe}. Valid arguments are: #{TIMEFRAMES}"
end

def validate_symbols(symbols)
return if symbols.is_a?(String)
return if symbols.is_a?(Array) && symbols.all?{ |symbol| symbol.is_a?(String) }
raise ArgumentError, "Invalid symbols: #{symbols.inspect}. Symbols must be a String or an array of strings."
end
end
end
Expand Down
33 changes: 21 additions & 12 deletions spec/alpaca/trade/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,32 +83,41 @@
end

describe '#bars' do
it 'returns Bar objects for one symbol', :vcr do
bars = subject.bars('1D', ['CRM'])
expect(bars['CRM']).to be_an(Array)
it 'returns Bar objects for one symbol as Array', :vcr do
bars = subject.bars(timeframe: '1D', symbols: ['CRM'], start_date: Date.today - 10)
expect(bars['bars']['CRM']).to be_an(Array)

bar = bars['CRM'].first
bar = bars['bars']['CRM'].first
expect(bar).to be_an(Alpaca::Trade::Api::Bar)
expect(bar.close).to eq(160.57)
expect(bar.close).to eq(223.84)
end

it 'returns Bar objects for one symbol as String', :vcr do
bars = subject.bars(timeframe: '1D', symbols: 'CRM', start_date: Date.today - 10)
expect(bars['bars']['CRM']).to be_an(Array)

bar = bars['bars']['CRM'].first
expect(bar).to be_an(Alpaca::Trade::Api::Bar)
expect(bar.close).to eq(223.84)
end

it 'returns Bar objects for multiple symbols', :vcr do
bars = subject.bars('1D', %w[CRM FB AMZN])
expect(bars['FB']).to be_an(Array)
bars = subject.bars(timeframe: '1D', symbols: %w[CRM FB AMZN], start_date: Date.today - 10)
expect(bars['bars']['FB']).to be_an(Array)

bar = bars['AMZN'].first
bar = bars['bars']['AMZN'].first
expect(bar).to be_an(Alpaca::Trade::Api::Bar)
end

it 'accepts limit as parameter', :vcr do
bars = subject.bars('1D', ['CRM'], limit: 10)
expect(bars['CRM']).to be_an(Array)
expect(bars['CRM'].size).to eq(10)
bars = subject.bars(timeframe: '1D', symbols: ['CRM'], limit: 10, start_date: Date.today - 100)
expect(bars['bars']['CRM']).to be_an(Array)
expect(bars['bars']['CRM'].size).to eq(10)
end

it 'doesnt accept invalid time frames' do
expect {
subject.bars('1FOO', ['CRM'])
subject.bars(timeframe: 'bogus', symbols: 'CRM', limit: 10, start_date: Date.today - 100)
}.to raise_error(ArgumentError)
end
end
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Large diffs are not rendered by default.

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading