-
Notifications
You must be signed in to change notification settings - Fork 8
/
Kraken.lua
369 lines (314 loc) · 10 KB
/
Kraken.lua
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
-- Inofficial Kraken Extension (www.kraken.com) for MoneyMoney
-- Fetches balances from Kraken API and returns them as securities
--
-- Username: Kraken API Key
-- Password: Kraken API Secret
--
-- Copyright (c) 2024 aaronk6, zacczakk
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
WebBanking{
version = 1.12,
url = "https://api.kraken.com",
description = "Fetch balances from Kraken API and list them as securities",
services= { "Kraken Account" },
}
local apiKey
local apiSecret
local apiVersion = 0
local currency = "EUR" -- fixme: Don't hardcode
local currencyName = "ZEUR" -- fixme: Don't hardcode
local stakeSuffix = '.S'
local optInRewardsSuffix = '.M'
local bitcoin = 'XXBT'
local ethereum = 'XETH'
local market = "Kraken"
local accountName = "Balances"
local accountNumber = "Main"
local balances
-- The currency names cannot be retrieved via the API, therefore hardcoding them (could use
-- web scraping instead).
-- Source: https://support.kraken.com/hc/en-us/articles/201893658-Currency-pairs-available-for-trading-on-Kraken
-- Retrieved on: May 7, 2019
-- Further currency names added on July 19, 2022, February 9, 2023, and April 11, 2024, but the list is still incomplete.
local currencyNames = {
-- crypto
AAVE = "Aave",
ADA = "Cardano",
ALGO = "Algorand",
APE = "ApeCoin",
ARB = "Arbitrum",
ASTR = "Astar",
ATOM = "Cosmos",
AVAX = "Avalanche",
BCH = "Bitcoin Cash",
COMP = "Compound",
DAI = "Dai",
DASH = "Dash",
DOT = "Polkadot",
DOT28 = "Polkadot Fixed 28",
DYDX = "dYdX",
DYM = "Dymension",
EOS = "EOS",
ETH2 = "Ethereum 2.0",
ETHW = "Ethereum (PoW)",
FET = "Fetch.ai",
FIL = "Filecoin",
FTM = "Fantom",
GALA = "Gala Games",
GNO = "Gnosis",
INJ = "Injective",
LINK = "Chainlink",
LUNA = "Terra Classic",
LUNA2 = "Terra 2.0",
MATIC = "Polygon",
MINA = "Mina",
OCEAN = "OCEAN Token",
PEPE = "Pepe",
PERP = "Perpetual Protocol",
QTUM = "QTUM",
RLC = "iExec RLC",
RUNE = "THORChain",
SEI = "Sei",
SHIB = "Shiba Inu",
SOL = "Solana",
SPELL = "Spell Token",
STRK = "Starknet Token",
STX = "Stacks",
SUI = "Sui",
TIA = "Celestia",
TRX = "Tron",
UNI = "Uniswap",
USDC = "USD Coin",
USDT = "Tether (Omni Layer)",
WIF = "dogwifhat",
WOO = "Woo Network",
WBTC = "Wrapped Bitcoin",
XETC = "Ethereum Classic",
XETH = "Ethereum",
XLTC = "Litecoin",
XMLN = "Watermelon",
XREP = "Augur",
XTZ = "Tezos",
XXBT = "Bitcoin",
XBT = "Bitcoin",
XXDG = "Dogecoin",
XXLM = "Stellar Lumens",
XXMR = "Monero",
XXRP = "Ripple",
XZEC = "Zcash",
-- fiat
ZCAD = "Canadian Dollar",
ZEUR = "Euro",
ZGBP = "Great British Pound",
ZJPY = "Japanese Yen",
ZUSD = "US Dollar"
}
function SupportsBank (protocol, bankCode)
return protocol == ProtocolWebBanking and bankCode == "Kraken Account"
end
function InitializeSession (protocol, bankCode, username, username2, password, username3)
apiKey = username
apiSecret = password
balances = queryPrivate("Balance")
assetPairs = queryPublic("AssetPairs")
prices = queryPublic("Ticker", { pair = table.concat(buildPairs(balances, assetPairs), ',') })
end
function ListAccounts (knownAccounts)
local account = {
name = accountName,
accountNumber = accountNumber,
currency = currency,
portfolio = true,
type = "AccountTypePortfolio"
}
return {account}
end
function RefreshAccount (account, since)
local name
local pair, bitcoinPair, targetCurrency, price
local s = {}
for key, value in pairs(balances) do
pair, targetCurrency = getPairInfo(key)
name = resolveCurrencyName(key)
if prices[pair] ~= nil or key == currencyName then
price = prices[pair] ~= nil and prices[pair]["b"][1] or 1
-- If this currency pair cannot be changed to fiat directly, we get the price
-- in Bitcoin or Ethereum here and need to convert it to the correct fiat amount.
if targetCurrency == bitcoin then
price = price * prices[getPairInfo(bitcoin)]["b"][1]
elseif targetCurrency == ethereum then
price = price * prices[getPairInfo(ethereum)]["b"][1]
end
if tonumber(value) > 0 then
s[#s+1] = {
name = name,
market = market,
currency = nil,
quantity = value,
price = price
}
end
end
end
return {securities = s}
end
function EndSession ()
end
function resolveCurrencyName(key)
local keyWithoutSuffix = removeSuffix(removeSuffix(key, stakeSuffix), optInRewardsSuffix)
local isStaked = key ~= keyWithoutSuffix
if isStaked and currencyNames[keyWithoutSuffix] ~=nil then
return currencyNames[keyWithoutSuffix] .. ' (staked)'
elseif currencyNames[key] then
return currencyNames[key]
end
-- If we cannot resolve the key to a name, return the unmodified key.
return key
end
function queryPrivate(method, request)
if request == nil then
request = {}
end
local path = string.format("/%s/private/%s", apiVersion, method)
local nonce = string.format("%d", math.floor(MM.time() * 1000000))
request["nonce"] = nonce
local postData = httpBuildQuery(request)
local apiSign = MM.hmac512(MM.base64decode(apiSecret), path .. hex2str(MM.sha256(nonce .. postData)))
local headers = {}
headers["API-Key"] = apiKey
headers["API-Sign"] = MM.base64(apiSign)
connection = Connection()
content = connection:request("POST", url .. path, postData, nil, headers)
json = JSON(applyFillerWorkaround(content))
return json:dictionary()["result"]
end
function queryPublic(method, request)
local path = string.format("/%s/public/%s", apiVersion, method)
local queryParams = ""
if request ~= nil and next(request) ~= nil then
queryParams = "?" .. httpBuildQuery(request)
end
local urlWithParams = url .. path .. queryParams
local content = connection:request("GET", urlWithParams, "")
local json = JSON(applyFillerWorkaround(content))
return json:dictionary()["result"]
end
function applyFillerWorkaround(content)
local fixVersion = '2.3.4'
if versionCompare(MM.productVersion, fixVersion) == -1 then
print("Adding filler to work around bug in product versions earlier than " .. fixVersion)
return '{"filler":"' .. string.rep('x', 2048) .. '",' .. string.sub(content, 2)
end
return content
end
function hex2str(hex)
return (hex:gsub("..", function (byte)
return string.char(tonumber(byte, 16))
end))
end
function httpBuildQuery(params)
local str = ''
for key, value in pairs(params) do
str = str .. key .. "=" .. value .. "&"
end
return str.sub(str, 1, -2)
end
function buildPairs(balances, assetPairs)
local pair = ''
local defaultPair = bitcoin .. currencyName
local t = {}
-- Always add default pair (i.e. XXBTZEUR)
-- If we don't add it, fiat price calculation for currencies that don't have a fiat
-- trading pair (such as Dogecoin) will fail in accounts that don't own Bitcoin.
table.insert(t, defaultPair)
for key, value in pairs(assetPairs) do
if balances[value["base"]] ~= nil or balances[value["quote"]] ~= nil then
if (key ~= defaultPair) then
table.insert(t, key)
end
end
end
return t
end
function getPairInfo(base)
-- support for staked coins (cut off stakeSuffix so that the currency can be found in asset pairs)
base = removeSuffix(base, stakeSuffix)
-- support for Opt-In Rewards, e.g. Bitcoin "staking" (XBT.M)
base = removeSuffix(base, optInRewardsSuffix)
-- rename "staked" XBT to XXBT so it can be found in the asset pair list
if base == 'XBT' then
base = 'XXBT'
end
-- rename ETH2 to XETH so it can be found in the asset pair list
if base == 'ETH2' then
base = 'XETH'
end
local opt1 = base .. currency
local opt2 = base .. currencyName
local opt3 = base .. bitcoin
if assetPairs[opt1] ~= nil then return opt1, currency
elseif assetPairs[opt2] ~= nil then return opt2, currencyName
-- opt3: currency cannot be changed to fiat directly, only to Bitcoin (applies to Lumen, Dogecoin)
elseif assetPairs[opt3] ~= nil then return opt3, bitcoin
end
return nil
end
function removeSuffix(str, suffix)
if ends_with(str, suffix) then
return str:sub(1, -#suffix-1)
end
return str
end
function versionCompare(version1, version2)
-- based on https://helloacm.com/how-to-compare-version-numbers-in-c/
local v1 = split(version1, '.')
local v2 = split(version2, '.')
if #v1 ~= #v2 then error("version1 and version2 need to have the same number of fields") end
for i = 1, #v1 do
local n1 = tonumber(v1[i])
local n2 = tonumber(v2[i])
if n1 > n2 then return 1
elseif n1 < n2 then return -1
end
end
return 0
end
function split(str, delimiter)
-- from http://lua-users.org/wiki/SplitJoin
local t, ll
t = {}
ll = 0
if #str == 1 then return {str} end
while true do
l = string.find(str, delimiter, ll, true)
if l ~= nil then
table.insert(t, string.sub(str, ll, l-1))
ll = l + 1
else
table.insert(t, string.sub(str, ll))
break
end
end
return t
end
function ends_with(str, ending)
-- from http://lua-users.org/wiki/StringRecipes
return ending == "" or str:sub(-#ending) == ending
end