-
Notifications
You must be signed in to change notification settings - Fork 2
/
sparkswap.js
179 lines (138 loc) · 5.68 KB
/
sparkswap.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
173
174
175
176
177
178
179
const EventEmitter = require('events')
const expandTilde = require('./utils/expand-tilde')
const basicAuth = require('./basic-auth')
const grpc = require('grpc')
const Big = require('big.js')
const { promisify } = require('util')
const path = require('path')
const { readFileSync } = require('fs')
const PROTO_OPTIONS = {
convertFieldsToCamelCase: true,
binaryAsBase64: true,
longsAsStrings: true,
enumsAsStrings: true
}
const brokerProto = grpc.load(path.resolve(__dirname, path.join('proto', 'broker.proto')), 'proto', PROTO_OPTIONS)
const DEFAULT_RPC_PORT = '27492'
class SparkswapClient {
constructor(configPath = '~/.sparkswap/config.js') {
const config = require(expandTilde(configPath))
this.address = config.rpcAddress || 'localhost:27492'
this.disableAuth = config.disableAuth || false
this.certPath = config.rpcCertPath || '~/.sparkswap/certs/broker-rpc-tls.cert'
this.username = config.rpcUser || 'sparkswap'
this.password = config.rpcPass || 'sparkswap'
const [host, port] = this.address.split(':')
// Set a default port if the port is not specified
if (!port) {
this.address = `${host}:${DEFAULT_RPC_PORT}`
}
if (this.disableAuth) {
this.credentials = grpc.credentials.createInsecure()
} else {
if (!this.username) throw new Error('No username is specified for authentication')
if (!this.password) throw new Error('No password is specified for authentication')
this.cert = readFileSync(expandTilde(this.certPath))
const channelCredentials = grpc.credentials.createSsl(this.cert)
const callCredentials = basicAuth.generateBasicAuthCredentials(this.username, this.password)
this.credentials = grpc.credentials.combineChannelCredentials(channelCredentials, callCredentials)
}
this.orderService = new brokerProto.broker.rpc.OrderService(this.address, this.credentials)
this.walletService = new brokerProto.broker.rpc.WalletService(this.address, this.credentials)
}
async cancelAll(market) {
const deadline = new Date().setSeconds(new Date().getSeconds() + 5)
const { blockOrders } = await promisify(this.orderService.getBlockOrders.bind(this.orderService))({ market }, { deadline })
const activeBlockOrders = blockOrders.filter(blockOrder => blockOrder.status === 'ACTIVE')
return Promise.all(activeBlockOrders.map((blockOrder) => promisify(this.orderService.cancelBlockOrder.bind(this.orderService))({ blockOrderId: blockOrder.blockOrderId }, { deadline })))
}
async place(market, side, price, amount) {
const deadline = new Date().setSeconds(new Date().getSeconds() + 5)
const { blockOrderId } = await promisify(this.orderService.createBlockOrder.bind(this.orderService))({
market,
side,
amount,
limitPrice: price,
timeInForce: 'GTC'
})
return blockOrderId
}
// Get the maximum size of the order based on your available trading capacity
// Returns in base units
async maxOrderSize(market, side, price) {
const deadline = new Date().setSeconds(new Date().getSeconds() + 5)
if (!['BID', 'ASK'].includes(side)) {
throw new Error(`Invalid side: ${side}`)
}
const {
baseSymbolCapacities,
counterSymbolCapacities
} = await promisify(this.walletService.getTradingCapacities.bind(this.walletService))(
{ market },
{ deadline }
)
let receiveCapacity
let sendCapacity
// bid buys (receives) base
if (side === 'BID') {
receiveCapacity = Big(baseSymbolCapacities.availableReceiveCapacity)
sendCapacity = Big(counterSymbolCapacities.availableSendCapacity).div(price)
} else {
receiveCapacity = Big(counterSymbolCapacities.availableReceiveCapacity).div(price)
sendCapacity = Big(baseSymbolCapacities.availableSendCapacity)
}
// leave some buffer
sendCapacity = sendCapacity.times(1 - 0.05)
receiveCapacity = receiveCapacity.times(1 - 0.05)
if (receiveCapacity.gt(sendCapacity)) {
return sendCapacity.toFixed(8)
}
return receiveCapacity.toFixed(8)
}
getOrder(id, callback) {
const deadline = new Date().setSeconds(new Date().getSeconds() + 5)
this.orderService.getBlockOrder({ blockOrderId: id }, { deadline }, callback)
}
watchOrderFillAmounts(id, interval = 5000, fillAmount = 0, emitter = new EventEmitter()) {
this.getOrder(id, (err, order) => {
if (err) {
return emitter.emit('error', err)
}
const newFillAmount = order.fillAmount || '0'
if(Big(newFillAmount).gt(fillAmount)) {
emitter.emit('fill', {
amount: Big(newFillAmount).minus(fillAmount).toFixed(8),
price: order.limitPrice
})
}
if (order.status === 'FAILED') {
return emitter.emit('error', new Error(`Order ${id} is in a FAILED state.`))
}
if (order.status === 'COMPLETE') {
return emitter.emit('done', order.status)
}
if (order.status === 'CANCELLED') {
return emitter.emit('done', order.status)
}
setTimeout(() => {
this.watchOrderFillAmounts(id, interval, newFillAmount, emitter)
}, interval)
})
return emitter
}
async watchOrder(id, interval = 5000) {
const deadline = new Date().setSeconds(new Date().getSeconds() + 5)
const order = await promisify(this.orderService.getBlockOrder.bind(this.orderService))({ blockOrderId: id }, { deadline })
if (order.status === 'FAILED') {
return 'FAILED'
}
if (order.status === 'COMPLETE') {
return 'COMPLETE'
}
if (order.status === 'CANCELLED') {
return 'CANCELLED'
}
return this.watchOrder(id, interval)
}
}
module.exports = new SparkswapClient(process.env.npm_package_config_sparkswap_config_path)