-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitfinex-utils.js
More file actions
178 lines (157 loc) · 4.85 KB
/
Copy pathbitfinex-utils.js
File metadata and controls
178 lines (157 loc) · 4.85 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
import BFX from 'bitfinex-api-node'
import fs from 'fs'
import createLogger from './logging.js'
import { BfxPerps } from './bfx/index.js'
const logger = createLogger('bfx')
const apiKey = process.env.BITFINEX_API_KEY
const apiSecret = process.env.BITFINEX_API_KEY_SECRET
const bfx = new BFX({ apiKey, apiSecret })
export async function getWallets() {
const rest = bfx.rest()
return await rest.wallets()
}
export async function ledgers(params) {
const rest = bfx.rest()
return await rest.ledgers(params)
}
export function onStatusHandlerCreator(statusKey, onStatus) {
const state = {
currentEventTsValue: {},
fundingValue: {}
}
function resetState() {
state.currentEventTsValue = {}
state.fundingValue = {}
}
function onStatusHandler(status) {
const currentEventTs = (state.currentEventTsValue[statusKey] =
state.currentEventTsValue[statusKey] || status[7])
const funding = (state.fundingValue[statusKey] = (status[11] || state.fundingValue[statusKey]))
const statusTs = status[0]
if (currentEventTs != status[7]) {
/* Got new funding event TS, wait until the status TS is
* bigger than the last event TS before triggering the onStatus
* callback and updating the currentEventTsValue to the new one.
*/
if (status[0] < currentEventTs) {
return
}
const diffTs = (-currentEventTs + statusTs)
logger.debug(
'status [next event ts changed diffTs=%d] eventTs=%d, nextTs=%d, markPrice=%f, funding0=%f, funding1=%f',
diffTs,
status[0],
status[7],
status[14],
funding,
status[11]
)
state.currentEventTsValue[statusKey] = status[7]
state.fundingValue[statusKey] = status[11]
if (onStatus) {
try {
onStatus({
statusTs,
currentEventTs,
nextTs: status[7],
markPrice: status[14],
funding,
status,
})
} catch (err) {
logger.error(err)
}
}
}
}
return { state, resetState, onStatusHandler }
}
export async function subscribeTrades(
{ symbol, statusKey },
onTrade,
onStatus
) {
const ws = bfx.ws(2, { autoReconnect: true })
let trades = {}
ws.onAccountTradeEntry({ symbol }, (trade) => {
logger.debug('trade entry', trade)
const tradeId = trade[0]
trades[tradeId] = trade
})
ws.onAccountTradeUpdate({ symbol }, (trade) => {
logger.debug('trade update', trade)
const tradeId = trade[0]
const teData = trades[tradeId]
if (!!teData) {
delete trades[tradeId]
if (onTrade)
onTrade({
id: tradeId,
symbol: trade[1],
mts: trade[2],
orderId: trade[3],
execAmount: trade[4],
execPrice: trade[5],
orderType: trade[6],
orderPrice: trade[7],
maker: trade[8] === 1,
fee: trade[9],
feeCurrency: trade[10],
clientOrderId: trade[11],
})
}
})
const { resetState: resetOnStatusState, onStatusHandler } =
onStatusHandlerCreator(statusKey, onStatus)
ws.onStatus({ key: statusKey }, onStatusHandler)
ws.on('error', (e) => logger.debug("ws :: error %j", e))
ws.on('auth', () => logger.debug('auth :: authenticated'))
ws.on('open', async () => {
logger.debug('open :: subscribing to channels')
trades = {}
resetOnStatusState()
try {
logger.debug('open :: subscribing trades on %s', symbol)
await ws.subscribeTrades(symbol)
logger.debug('open :: subscribed trades on %s', symbol)
logger.debug('open :: subscribing status on %s', statusKey)
await ws.subscribeStatus(statusKey)
logger.debug('open :: subscribed status on %s', statusKey)
} catch (err) {
logger.error('open :: error', err)
}
})
logger.debug('subscribeTrades :: opening websocket')
await ws.open()
logger.debug('subscribeTrades :: opened websocket, authenticating')
await ws.auth()
logger.debug('subscribeTrades :: websocket authenticated')
return { close: () => {
logger.debug('Closing WS connection...')
return ws.close()
}, _ws: ws }
}
export async function getBalance(type, currency) {
const entries = (await ledgers({ filters: { ccy: currency } }))
.filter((l) => l[2] === type && l[1] === currency)
.sort((a, b) => b[3] - a[3] || b[0] - a[0])
if (entries.length > 0) {
return entries[0][6]
} else {
/* Fallback to balance info (imprecise) */
const wallets = await getWallets().filter(
(wallet) =>
wallet.type.toLowerCase() === walletType.toLowerCase() &&
wallet.currency.toLowerCase() === walletCurrency.toLowerCase()
)
if (wallets.length > 1) {
throw new Error('[INFO] getBalance - duplicated (type, currency) pair')
}
return wallets[0][2]
}
}
export const BFXApi = {
bfx_node: bfx,
getBalance,
BfxPerps,
}