-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBitget.lua
More file actions
602 lines (511 loc) · 21.5 KB
/
Bitget.lua
File metadata and controls
602 lines (511 loc) · 21.5 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
-- Unofficial Bitget Extension (www.bitget.com) for MoneyMoney
-- Fetches Spot balances and Futures positions via Bitget API
-- Returns them as securities
--
-- MIT License
--
-- Copyright (c) 2025 Robert Gering
--
-- 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.1,
country = "de",
description = string.format(MM.localizeText("Fetch balances and positions from %s"), "Bitget"),
services = {"Bitget"},
}
-- State
local connection
local apiKey
local apiSecret
local passphrase
local baseUrl = "https://api.bitget.com"
-- Exchange rate cache
local cachedFxRates = {} -- currency pair (e.g. EUR/USD) : rate
-- Constants
local SPOT_ACCOUNT_NAME = "Bitget Spot"
local FUTURES_ACCOUNT_NAME = "Bitget Futures"
-- String extensions for XML parsing
string.parseTagContent = function(s, tag)
return s:match("<" .. tag .. ".->(.-)</" .. tag .. ">")
end
string.parseTag = function(s, tag)
return s:match("<" .. tag .. ".-/>")
end
string.parseTags = function(s, tag)
return s:gmatch("<" .. tag .. ".-/>")
end
string.parseArgs = function(s)
local args = {}
s:gsub("([%-%w]+)=([\"'])(.-)%2", function(w, _, a)
args[w] = a
end)
return args
end
-- Currency conversion functions
function fetchFxRate(base, quote)
if quote == "EUR" then
return 1 / fetchFxRate(quote, base)
end
if base == "EUR" then
local content = Connection():request("GET", "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
for cube in content:parseTags("Cube") do
local conversion = cube:parseArgs()
if conversion.currency == quote then
MM.printStatus("Wechselkurs geladen: " .. base .. "/" .. quote .. " @ " .. conversion.rate)
return tonumber(conversion.rate)
end
end
end
MM.printStatus("Wechselkurs nicht verfügbar für " .. base .. "/" .. quote)
-- Cache failed lookups to avoid repeated API calls
setFxRate(base, quote, nil)
return nil
end
function getFxRate(base, quote)
if base:lower() == quote:lower() then
return 1
end
-- Use cached rate
local pair = base:upper() .. "/" .. quote:upper()
if cachedFxRates[pair] ~= nil then
if cachedFxRates[pair] == "not_available" then
return 1 -- fallback to 1:1 if cached as not available
end
return cachedFxRates[pair]
end
-- Use cached rate of reversed pair
local reversedPair = quote:upper() .. "/" .. base:upper()
if cachedFxRates[reversedPair] ~= nil then
if cachedFxRates[reversedPair] == "not_available" then
return 1 -- fallback to 1:1 if cached as not available
end
return 1/cachedFxRates[reversedPair]
end
-- Fetch rate as fallback
local rate = fetchFxRate(base, quote)
if rate then
setFxRate(base, quote, rate)
return rate
end
return 1 -- fallback to 1:1 if no rate found
end
function convertToEUR(amount, currency)
if currency == "EUR" then
return amount
elseif currency == "USDT" then
-- Treat USDT as USD for conversion
local rate = getFxRate("EUR", "USD")
if not rate then
MM.printStatus("Fallback: USDT wird als 1:1 USD behandelt")
rate = 1
end
return amount / rate
else
local rate = getFxRate("EUR", currency)
if not rate then
MM.printStatus("Problem: Kein Wechselkurs für " .. currency .. ", verwende 1:1 Fallback")
return amount
end
return amount / rate
end
end
function getFxRateToBase(currency)
-- Special handling for USDT - treat as USD
if currency == "USDT" then
return getFxRate("EUR", "USD")
end
return getFxRate("EUR", currency)
end
function setFxRate(base, quote, rate)
if base ~= quote then
local pair = base:upper() .. "/" .. quote:upper()
if cachedFxRates[pair] == nil then
if rate then
cachedFxRates[pair] = rate
else
cachedFxRates[pair] = "not_available"
end
end
end
end
-- Helper functions
local allCoins = nil -- Cache for CoinGecko coin data
-- Hardcoded coins table for major cryptocurrencies to avoid symbol collisions
local coins = {
btc = { id = "bitcoin", name = "Bitcoin" },
eth = { id = "ethereum", name = "Ethereum" },
ltc = { id = "litecoin", name = "Litecoin" },
doge = { id = "dogecoin", name = "Dogecoin" },
dot = { id = "polkadot", name = "Polkadot" },
ada = { id = "cardano", name = "Cardano" },
sol = { id = "solana", name = "Solana" },
avax = { id = "avalanche-2", name = "Avalanche" },
matic = { id = "matic-network", name = "Polygon" },
link = { id = "chainlink", name = "Chainlink" },
uni = { id = "uniswap", name = "Uniswap" },
atom = { id = "cosmos", name = "Cosmos" },
xrp = { id = "ripple", name = "XRP" },
bnb = { id = "binancecoin", name = "BNB" },
usdc = { id = "usd-coin", name = "USD Coin" },
usdt = { id = "tether", name = "Tether" }
}
function fetchAllCoins()
MM.printStatus("Lade Crypto Coins von CoinGecko...")
local connection = Connection()
local content = connection:request("GET", "https://api.coingecko.com/api/v3/coins/list")
if content then
local coinList = JSON(content):dictionary()
local coinMap = {}
for _, coin in ipairs(coinList) do
-- Only add if not already present (first occurrence wins)
if not coinMap[coin.symbol] then
coinMap[coin.symbol] = coin
end
end
return coinMap
end
return nil
end
function lookupCoinName(symbol)
local lowerSymbol = symbol:lower()
-- First, try hardcoded local coins
local coin = coins[lowerSymbol]
if coin == nil then
-- If not found, try to fetch all coins from CoinGecko
if allCoins == nil then
allCoins = fetchAllCoins()
if allCoins == nil then
MM.printStatus("Crypto Coins konnten nicht geladen werden")
return symbol
end
end
coin = allCoins[lowerSymbol]
end
if coin == nil then
return symbol -- fallback to symbol if not found
end
return coin.name
end
function fetchCurrentPrice(symbol)
local response = makeRequest("GET", "/api/mix/v1/market/ticker", {symbol = symbol}, nil)
if response and response.code == "00000" and response.data then
return tonumber(response.data.last) or tonumber(response.data.close) or 0
end
MM.printStatus("Fallback: Kein aktueller Preis für " .. symbol)
return 0
end
function createSignature(timestamp, method, requestPath, queryString, body)
local message = timestamp .. method .. requestPath
if queryString and queryString ~= "" then
message = message .. "?" .. queryString
end
if body and body ~= "" then
message = message .. body
end
local signature = MM.hmac256(apiSecret, message)
return MM.base64(signature)
end
function makeRequest(method, path, queryParams, body)
local timestamp = tostring(os.time() * 1000)
local queryString = ""
if queryParams then
local params = {}
for k, v in pairs(queryParams) do
table.insert(params, k .. "=" .. v)
end
queryString = table.concat(params, "&")
if queryString ~= "" then
path = path .. "?" .. queryString
end
end
local signature = createSignature(timestamp, method, path:match("^([^?]+)"), queryString, body or "")
local headers = {
["ACCESS-KEY"] = apiKey,
["ACCESS-SIGN"] = signature,
["ACCESS-TIMESTAMP"] = timestamp,
["ACCESS-PASSPHRASE"] = passphrase,
["Content-Type"] = "application/json"
}
local content = connection:request(method, baseUrl .. path, body, nil, headers)
if content then
local json = JSON(content)
return json:dictionary()
end
return nil
end
-- MoneyMoney API implementation
function SupportsBank(protocol, bankCode)
return protocol == ProtocolWebBanking and bankCode == "Bitget"
end
function InitializeSession(protocol, bankCode, username, username2, password, username3)
MM.printStatus("Initialisiere Bitget-Verbindung")
apiKey = username
apiSecret = username2
passphrase = password
if not apiKey or apiKey == "" then
MM.printStatus("Fehler: API Key fehlt")
return LoginFailed
end
if not apiSecret or apiSecret == "" then
MM.printStatus("Fehler: API Secret fehlt")
return LoginFailed
end
if not passphrase or passphrase == "" then
MM.printStatus("Fehler: Passphrase fehlt")
return LoginFailed
end
connection = Connection()
-- Test connection with a simple API call
local response = makeRequest("GET", "/api/spot/v1/public/time", nil, nil)
if not response or response.code ~= "00000" then
MM.printStatus("Fehler: Verbindung fehlgeschlagen")
return LoginFailed
end
MM.printStatus("Verbindung erfolgreich")
end
function ListAccounts(knownAccounts)
local accounts = {}
-- Spot Account
table.insert(accounts, {
name = SPOT_ACCOUNT_NAME,
owner = apiKey:sub(1, 8) .. "...",
accountNumber = "SPOT",
currency = "EUR",
type = AccountTypePortfolio,
portfolio = true
})
-- Futures Account
table.insert(accounts, {
name = FUTURES_ACCOUNT_NAME,
owner = apiKey:sub(1, 8) .. "...",
accountNumber = "FUTURES",
currency = "EUR",
type = AccountTypePortfolio,
portfolio = true
})
return accounts
end
function RefreshAccount(account, since)
local securities = {}
if account.accountNumber == "SPOT" then
MM.printStatus("Lade Spot-Guthaben...")
securities = fetchSpotBalances()
elseif account.accountNumber == "FUTURES" then
MM.printStatus("Lade Futures-Positionen...")
securities = fetchFuturesPositions()
end
return {securities = securities}
end
function fetchSpotBalances()
local securities = {}
local response = makeRequest("GET", "/api/spot/v1/account/assets", nil, nil)
if not response or response.code ~= "00000" then
MM.printStatus("Fehler beim Abrufen der Spot-Guthaben")
return securities
end
for _, asset in ipairs(response.data or {}) do
local coin = asset.coinName or asset.coinDisplayName
if not coin then
-- Skip asset if no coin name available
MM.printStatus("Überspringe Asset ohne Coin-Name")
goto continue
end
local available = tonumber(asset.available) or 0
local frozen = tonumber(asset.frozen) or 0
local locked = tonumber(asset.locked) or 0
local total = available + frozen + locked
if total > 0 then
-- Get current price in USD
local priceUSD = 0
local priceEUR = 0
local baseCurrency = "USD"
local fiat = false
-- Handle different coin types for price lookup
if coin == "USDT" then
priceUSD = 1
elseif coin == "USD" then
-- USD is a fiat currency
priceUSD = 1
fiat = true
elseif coin == "EUR" then
-- EUR is a fiat currency
priceEUR = 1
fiat = true
else
-- For other cryptocurrencies, fetch the current price
local priceResponse = makeRequest("GET", "/api/spot/v1/market/ticker", {symbol = coin .. "USDT_SPBL"}, nil)
if priceResponse and priceResponse.code == "00000" and priceResponse.data then
priceUSD = tonumber(priceResponse.data.close) or 0
end
end
-- Convert amount to EUR
local amountEUR = 0
local amountUSD = 0
if priceUSD > 0 then
amountUSD = total * priceUSD
amountEUR = convertToEUR(amountUSD, "USD")
elseif priceEUR > 0 then
-- If we have a EUR price, use it directly
amountEUR = total * priceEUR
else
MM.printStatus("Kein Preis für " .. coin)
end
-- Coin name (e.g., AVAX -> Avalanche)
local coinName = coin and lookupCoinName(coin) or coin
table.insert(securities, {
name = coin,
market = "Bitget Spot",
quantity = total,
currencyOfQuantity = fiat and coin:sub(1, 3) or nil, -- Use first 3 letters as currency code
price = priceUSD,
currencyOfPrice = baseCurrency,
originalCurrencyAmount = amountUSD or amountEUR,
currencyOfOriginalAmount = baseCurrency,
exchangeRate = getFxRateToBase(baseCurrency),
amount = amountEUR,
userdata = {}
})
-- Custom fields for additional information
if not fiat then
table.insert(securities[#securities].userdata, { key = "Coin", value = coinName })
end
end
::continue::
end
MM.printStatus("Spot-Guthaben geladen")
return securities
end
function fetchFuturesPositions()
local securities = {}
-- First, fetch futures account balance (available funds)
local balanceResponse = makeRequest("GET", "/api/mix/v1/account/accounts", {productType = "umcbl"}, nil)
if balanceResponse and balanceResponse.code == "00000" and balanceResponse.data then
for _, account in ipairs(balanceResponse.data or {}) do
-- Try different fields for available balance
local available = tonumber(account.available) or tonumber(account.equity) or tonumber(account.crossMaxAvailable) or 0
local marginCoin = account.marginCoin or "USDT"
if available > 0 then
local availableEUR = convertToEUR(available, marginCoin == "USDT" and "USD" or marginCoin)
table.insert(securities, {
name = marginCoin,
market = "Bitget Futures",
quantity = available,
exchangeRate = getFxRateToBase(marginCoin == "USDT" and "USD" or marginCoin),
amount = availableEUR
})
end
end
end
-- Fetch all futures positions
local productTypes = {"umcbl", "dmcbl", "cmcbl"} -- USDT, Universal, USDC perpetuals
for _, productType in ipairs(productTypes) do
local response = makeRequest("GET", "/api/mix/v1/position/allPosition-v2", {productType = productType}, nil)
if response and response.code == "00000" and response.data then
for _, position in ipairs(response.data or {}) do
if tonumber(position.total) and tonumber(position.total) > 0 then
local symbol = position.symbol:gsub("_.*", "") -- Remove suffix like _UMCBL
local cryptoSymbol = symbol:match("([%w]+)USDT") or symbol:match("([%w]+)USDC") or symbol:match("([%w]+)BTC") or symbol:match("([%w]+)ETH")
local holdSide = position.holdSide
local leverage = tonumber(position.leverage) or 1
local unrealizedPnl = tonumber(position.unrealizedPL) or 0
local marketPrice = tonumber(position.marketPrice) or 0
local avgPrice = tonumber(position.averageOpenPrice) or 0
-- Check for margin mode (isolated vs cross)
local marginMode = position.marginMode or "unknown"
local total = tonumber(position.total) or 0
local margin = tonumber(position.margin) or 0
MM.printStatus("Futures-Position: " .. symbol .. " (" .. holdSide .. ")" .. " - Leverage: " .. leverage .. "x " .. marginMode .. " - Margin: " .. margin .. " - Price: " .. marketPrice .. " - Average Price: " .. avgPrice .. " - P&L: " .. unrealizedPnl .. " - Total: " .. total)
-- Extract quote currency from symbol and map to 3-digit codes
local quoteCurrency = "USD" -- Default (USDT -> USD for MoneyMoney)
local quoteCurrencyDisplay = "USDT" -- For display purposes
if symbol:match("USDT$") then
quoteCurrency = "USD"
quoteCurrencyDisplay = "USDT"
elseif symbol:match("USDC$") then
quoteCurrency = "USD"
quoteCurrencyDisplay = "USDC"
elseif symbol:match("BTC$") then
quoteCurrency = "BTC"
quoteCurrencyDisplay = "BTC"
elseif symbol:match("ETH$") then
quoteCurrency = "ETH"
quoteCurrencyDisplay = "ETH"
end
-- Handle Long and Short positions correctly
local adjustedQuantity = total
local adjustedPrice = marketPrice
local adjustedPurchasePrice = avgPrice
if holdSide == "short" then
adjustedQuantity = -total -- Short positions are negative in MoneyMoney
end
-- For correct portfolio value: use margin + unrealized P&L
local marginUSD = tonumber(position.margin) or 0
local marginCurrency = position.marginCoin or quoteCurrency
-- Convert USDT to USD for MoneyMoney compatibility
if marginCurrency == "USDT" then
marginCurrency = "USD"
end
local marginEUR = convertToEUR(marginUSD, marginCurrency)
local unrealizedPnlEUR = convertToEUR(unrealizedPnl, quoteCurrency)
local amountEUR = convertToEUR(unrealizedPnl, quoteCurrency)
local relativePnl = marginUSD ~= 0 and (unrealizedPnl / marginUSD * 100) or 0
local currencyOfQuantity = cryptoSymbol and cryptoSymbol:sub(1,3) or nil
-- Format symbol with slash (e.g., AVAXUSDT -> AVAX/USDT)
local formattedSymbol = symbol:gsub("USDT$", "/USDT"):gsub("USDC$", "/USDC"):gsub("BTC$", "/BTC"):gsub("ETH$", "/ETH")
-- Coin name (e.g., AVAX -> Avalanche)
local coinName = cryptoSymbol and lookupCoinName(cryptoSymbol) or cryptoSymbol
-- Format profit string exactly as MoneyMoney expects
local profit = string.format("%.02f EUR / ", unrealizedPnlEUR) .. string.format("%.05f", relativePnl) .. " %"
-- Create a unique identifier for the position
local positionIdentifier = string.format("%s %s-%dx-%s", symbol, holdSide, leverage, marginMode)
table.insert(securities, {
name = formattedSymbol,
market = "Bitget Futures",
quantity = adjustedQuantity,
-- currencyOfQuantity = currencyOfQuantity,
-- originalCurrencyAmount = marginUSD,
-- currencyOfOriginalAmount = marginCurrency,
price = adjustedPrice,
--currencyOfPrice = quoteCurrency,
purchasePrice = adjustedPurchasePrice,
--currencyOfPurchasePrice = quoteCurrency,
exchangeRate = getFxRateToBase(quoteCurrency),
amount = marginEUR + amountEUR,
isin = positionIdentifier, -- Use position identifier as ISIN
userdata = {
{ key="_profit", value=profit },
-- Custom fields for additional information
{ key="Coin", value=coinName },
{ key="Hebel", value=leverage .. "x" },
{ key="Margin", value=string.format("%.02f €", marginEUR) },
-- { key="Margin Coin", value=marginCoin },
-- { key="Symbol", value=symbol },
}
})
end
end
end
end
MM.printStatus("Futures-Positionen geladen")
return securities
end
function EndSession()
-- Nothing to do
end
-- SIGNATURE: MCwCFAvxxJEQqJ7YyXm49LDgsQ47T8C9AhRnIid+ufF7YqV3IF55wkhXbuY7nA==