-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.js
318 lines (272 loc) · 8.62 KB
/
service.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
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
const {
API_ERROR_CODE,
APIMarket,
LinearClient,
LinearPositionIdx,
WebsocketClient,
} = require("bybit-api");
/**
Either use environmental variables to try this, e.g. unix/mac:
APIKEY="APIKEYHERE" APISECRET="APISECRETHERE" ts-node src/exchanges/bybit/account-events/log-account-events-usdt.ts
or hardcode it:
const key = "APIKEYHERE";
const secret = "APISECRETHERE";
the below code reads it from env vars first. If none are provided, it defaults to the hardcoded strings:
**/
const apiKey = "DnoUBOw5xz4ThzogBc";
const apiSecret = "cjhCDKfl9I5veHWtcAp4uvTwLsKAo1zO6m4R";
const testnet = false;
/**
* This sample is a simple demonstration of opening and closing OneWay positions on USDT (linear) perps on bybit.
*/
// Purely for logging, connect to account websocket events to monitor activity
const Connect = connectAndListenToAccountWebsocketEvents(
apiKey,
apiSecret,
"spot"
);
// Start REST API calls for submitting orders
submitUsdtPerpOrders(apiKey, apiSecret);
// optional, but this could be used to make an async version of this that doesn't make REST API calls to check position changes
function connectAndListenToAccountWebsocketEvents(key, secret, apiMarket) {
const wsClient = new WebsocketClient({
key: key,
secret: secret,
market: apiMarket,
testnet: testnet,
});
wsClient.on("update", (data) => {
console.log("ws event: ", JSON.stringify(data, null, 2));
});
wsClient.on("open", (data) => {
console.log("ws connection opened:", data.wsKey);
});
wsClient.on("response", (data) => {
console.log("ws response: ", JSON.stringify(data, null, 2));
});
wsClient.on("reconnect", ({ wsKey }) => {
console.log("ws automatically reconnecting.... ", wsKey);
});
wsClient.on("reconnected", (data) => {
console.log("ws has reconnected ", data?.wsKey);
});
// subscribe to private endpoints
wsClient.subscribe(["position", "execution", "order", "wallet"]);
}
async function submitUsdtPerpOrders(apiKey, apiSecret) {
const restClient = new LinearClient({
key: apiKey,
secret: apiSecret,
testnet: testnet,
});
const TARGET_LEVERAGE = 5;
const TARGET_SYMBOL = "ETHUSDT";
const BTC_AMOUNT_TO_TRADE = 0.001;
const walletBalanceResponse = await restClient.getWalletBalance();
const usdtBalance = walletBalanceResponse.result.USDT?.available_balance;
console.log(
"usdtBalance: ",
usdtBalance
// JSON.stringify(walletBalanceResponse, null, 2),
);
// set mode to one-way (easier than hedge-mode, if you don't care for hedge mode)
const positionModeResult = await restClient.setPositionMode({
symbol: TARGET_SYMBOL,
mode: "MergedSingle",
});
if (
positionModeResult.ret_code === API_ERROR_CODE.POSITION_MODE_NOT_MODIFIED
) {
console.log("position mode was already correct: ", positionModeResult);
} else {
console.log("position mode change result: ", positionModeResult);
}
// log current positions (and leverage per symbol)
const positionResult = await restClient.getPosition({
symbol: TARGET_SYMBOL,
});
console.log(
"positions: ",
positionResult.result.map((pos) => {
return {
symbol: pos.symbol,
leverage: pos.leverage,
mode: pos.mode,
size: pos.size,
side: pos.side,
};
})
);
// change leverage, only if needed
const leverageToChange = positionResult.result.filter(
(pos) => pos.leverage !== TARGET_LEVERAGE
);
if (leverageToChange.length) {
const setLeverageResult = await restClient.setUserLeverage({
symbol: TARGET_SYMBOL,
buy_leverage: TARGET_LEVERAGE,
sell_leverage: TARGET_LEVERAGE,
});
console.log(
"setLeverageResult: ",
JSON.stringify(setLeverageResult, null, 2)
);
} else {
console.log("no leverage change needed");
}
console.log("entering long position: ");
const successEntryLong = await enterLongPosition(
restClient,
TARGET_SYMBOL,
BTC_AMOUNT_TO_TRADE
);
if (!successEntryLong) {
// dont continue on fail
return;
}
const sleepSecondsBetweenOrder = 1;
await new Promise((resolve) =>
setTimeout(resolve, sleepSecondsBetweenOrder * 1000)
);
console.log("closing long position: ");
const successExitLong = await closeLongPosition(restClient, TARGET_SYMBOL);
if (!successExitLong) {
// dont continue on fail
return;
}
await new Promise((resolve) =>
setTimeout(resolve, sleepSecondsBetweenOrder * 1000)
);
console.log("entering short position: ");
const successEntryShort = await enterShortPosition(
restClient,
TARGET_SYMBOL,
BTC_AMOUNT_TO_TRADE
);
if (!successEntryShort) {
// dont continue on fail
return;
}
await new Promise((resolve) =>
setTimeout(resolve, sleepSecondsBetweenOrder * 1000)
);
console.log("closing short position: ");
const successExitShort = await closeShortPosition(restClient, TARGET_SYMBOL);
if (!successExitShort) {
// dont continue on fail
return;
}
console.log("reached end - hit ctrl + C to kill the process");
}
async function enterLongPosition(restClient, symbol, quantity) {
// Open a long position by making a long entry order (buying so the position qty is positive)
const entryOrderResult = await restClient.placeActiveOrder({
side: "Buy",
symbol: symbol,
order_type: "Market",
qty: quantity,
time_in_force: "GoodTillCancel",
reduce_only: false,
close_on_trigger: false,
position_idx: LinearPositionIdx.OneWayMode,
});
if (entryOrderResult.ret_msg !== "OK") {
console.error(
`ERROR making long entry order: `,
JSON.stringify(entryOrderResult, null, 2)
);
return false;
}
console.log("success - long entry order: ", JSON.stringify(entryOrderResult));
return true;
}
// shorting is just making sure you have a negative position
async function enterShortPosition(restClient, symbol, quantity) {
// Open a short position by making a long entry order (selling so the position qty is negative)
const entryOrderResult = await restClient.placeActiveOrder({
side: "Sell",
symbol: symbol,
order_type: "Market",
qty: quantity,
time_in_force: "GoodTillCancel",
reduce_only: false,
close_on_trigger: false,
position_idx: LinearPositionIdx.OneWayMode,
});
if (entryOrderResult.ret_msg !== "OK") {
console.error(
`ERROR making long entry order: `,
JSON.stringify(entryOrderResult, null, 2)
);
return false;
}
console.log("success - long entry order: ", JSON.stringify(entryOrderResult));
return true;
}
async function closeLongPosition(restClient, symbol) {
const positionResult = await restClient.getPosition({
symbol: symbol,
});
const activePosition = positionResult.result.find(
(pos) => pos.symbol === symbol
);
console.log("active position: ", activePosition);
if (!activePosition || activePosition.side !== "Buy") {
console.error("no long position to close");
return false;
}
// submit reduce only sell to close long position
const closePositionResult = await restClient.placeActiveOrder({
side: "Sell",
symbol: symbol,
order_type: "Market",
qty: activePosition.size, // using position size from api response
time_in_force: "GoodTillCancel",
reduce_only: true,
close_on_trigger: false,
position_idx: LinearPositionIdx.OneWayMode,
});
if (closePositionResult.ret_msg !== "OK") {
console.error(
`error closing long position: `,
JSON.stringify(closePositionResult, null, 2)
);
return false;
}
console.log("success - reduce long position: ", closePositionResult);
return true;
}
async function closeShortPosition(restClient, symbol) {
const positionResult = await restClient.getPosition({
symbol: symbol,
});
const activePosition = positionResult.result.find(
(pos) => pos.symbol === symbol
);
console.log("active position: ", activePosition);
if (!activePosition || activePosition.side !== "Sell") {
console.error("no short position to close");
return false;
}
// submit reduce only buy to close short position
const closePositionResult = await restClient.placeActiveOrder({
side: "Buy",
symbol: symbol,
order_type: "Market",
qty: activePosition.size, // using position size from api response
time_in_force: "GoodTillCancel",
reduce_only: true,
close_on_trigger: false,
position_idx: LinearPositionIdx.OneWayMode,
});
if (closePositionResult.ret_msg !== "OK") {
console.error(
`error closing short position: `,
JSON.stringify(closePositionResult, null, 2)
);
return false;
}
console.log("success - reduce short position: ", closePositionResult);
return true;
}
module.export = Connect;