-
Notifications
You must be signed in to change notification settings - Fork 0
/
alpaca.js
173 lines (154 loc) · 5.23 KB
/
alpaca.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const got = require('./got.js')
const qs = require('querystring')
const assert = require('assert')
const data_host = 'https://data.alpaca.markets'
const api_host = 'https://api.alpaca.markets'
assert(process.env['APCA_API_KEY_ID'], "Must set APCA_API_KEY_ID")
assert(process.env['APCA_API_SECRET_KEY'], "Must set APCA_API_SECRET_KEY")
const auth_headers = {
'APCA-API-KEY-ID':process.env['APCA_API_KEY_ID'],
'APCA-API-SECRET-KEY':process.env['APCA_API_SECRET_KEY']
}
const tz = (date) => {
const timezoneOffsetInMinutes = date.getTimezoneOffset();
const timezoneOffsetHours = Math.abs(Math.floor(timezoneOffsetInMinutes / 60));
const timezoneOffsetMinutes = Math.abs(timezoneOffsetInMinutes % 60);
const timezoneSign = timezoneOffsetInMinutes < 0 ? '+' : '-';
const timezone = `${timezoneSign}${timezoneOffsetHours.toString().padStart(2, '0')}:${timezoneOffsetMinutes.toString().padStart(2, '0')}`;
return timezone
}
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())
+ tz(d)
}
const get_account_history = async function(period, timeframe, date_end) {
const request = await got(api_host+`/v2/account/portfolio/history?` +
qs.encode({period, timeframe, date_end}), {
headers:auth_headers
})
assert(request.statusCode == 200, `Failed to load account history ${JSON.stringify(request)}`)
return JSON.parse(request.body)
}
const get_latest_quote = async function(symbol) {
const request = await got(data_host+`/v2/stocks/${symbol}/quotes/latest`, {
headers:auth_headers
})
assert([200].includes(request.statusCode), `Failed to load latest quote ${JSON.stringify(request)}`)
return JSON.parse(request.body)
}
const get_latest_multitrade = async function(symbols) {
assert(Array.isArray(symbols), "Must pass array to multitrade")
const params = {
'symbols':symbols.join(',')
}
const request = await got(data_host+`/v2/stocks/trades/latest?${qs.encode(params)}`, {
headers:auth_headers
})
assert(request.statusCode == 200, `Failed to get latest trade ${JSON.stringify(request)}`)
return JSON.parse(request.body)
}
const get_latest_trade = async function(symbol) {
const request = await got(data_host+`/v2/stocks/${symbol}/trades/latest`, {
headers:auth_headers
})
assert(request.statusCode == 200, `Failed to get latest trade ${JSON.stringify(request)}`)
return JSON.parse(request.body)
}
const get_snapshot = async function(symbol) {
const request = await got(data_host+`/v2/stocks/${symbol}/snapshot`, {
headers:auth_headers
})
const response = JSON.parse(request.body)
const daily_is_today = moment().isSame(response.dailyBar.t, 'day')
if (daily_is_today) {
return response.prevDailyBar
}
else {
return response.dailyBar
}
}
const get_asset = async function(asset_id) {
const request = await got(api_host+`/v2/assets/${asset_id}`, {
headers:auth_headers
})
if (request.statusCode == 429) {
throw new Error('Rate Limit Exceeded')
}
return JSON.parse(request.body)
}
const big_board = [
'ARCA',
'NASDAQ',
'NYSE',
'BATS'
]
const get_equity_assets = async function() {
const request = await got(api_host + '/v2/assets', {
headers:auth_headers
})
const assets = JSON.parse(request.body)
.filter((a) => {return a.tradable == true})
.filter((a) => {return a.status == 'active'})
.filter((a) => {return big_board.includes(a.exchange)})
return assets
}
const get_bars = async (symbol, start, end, timeframe='1Min') => {
const parameters = {
timeframe: timeframe,
start: ISODateString(start),
end: ISODateString(end),
limit: 10000,
adjustment: 'all'
}
const url = `${data_host}/v2/stocks/${symbol}/bars` +
`?${new URLSearchParams(parameters)}`
const response = await got(url, {
headers: auth_headers
})
const data = JSON.parse(response.body)
let bars = data.bars
while(data.next_page_token) {
const url = `${data_host}/v2/stocks/${symbol}/bars` +
`?${new URLSearchParams(parameters)}&page_token=${data.next_page_token}`
const response = await got(url, {
headers: auth_headers
})
const data = JSON.parse(response.body)
bars = bars.concat(data.bars)
}
return bars
}
const get_calendar = async function(start, end) {
const params = qs.encode({
start:ISODateString(start),
end:ISODateString(end)
})
const request = await got(api_host+`/v2/calendar?${params}`, {
headers:auth_headers
})
return JSON.parse(request.body)
}
const get_clock = async function() {
const request = await got(api_host+"/v2/clock", {
headers:auth_headers
})
return JSON.parse(request.body)
}
module.exports = {
get_account_history,
get_latest_quote,
get_latest_multitrade,
get_latest_trade,
get_snapshot,
get_asset,
get_equity_assets,
get_calendar,
get_clock,
get_bars
}