forked from oboshto/tradie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
339 lines (280 loc) · 10.9 KB
/
index.ts
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
import {
getEMA,
getBB,
getRSI
} from './indicators'
import {
CRYPTO_COMPARE_API_KEY,
LOG_LEVEL,
CANDLE_AGGREGATE_MINUTES,
GET_MARKET_DATA_INTERVAL_SECONDS,
STOP_LOSS,
TAKE_PROFIT,
BUY_TOKEN_ADDRESS,
QUOTE_SYMBOL,
SLIPPAGE_PERCENT,
TRANSACTION_PRIORITY_FEE,
RSI_TO_BUY,
RSI_TO_SELL,
} from './constants'
import {
logger,
request,
sleep,
} from "./utils"
import {version} from './package.json'
import * as fs from "fs"
import {
getSolBalance,
getTokenAmountByAddress,
} from "./wallet";
import {buyToken} from "./trade";
let activePosition: any | null = null
const positionFilePath = './position.json'
let buySymbol: string
let quoteAddress: string
let solBalance: number
let buyTokenBalance: number
let buyTokenDecimals: number
let quoteTokenBalance: number
let quoteTokenDecimals: number
const main = async () => {
await init()
try {
await analyzeMarket()
setTimeout(runAnalyzeMarket, GET_MARKET_DATA_INTERVAL_SECONDS * 1000)
} catch (error) {
logger.error(error, 'Error occurred while analyzing market:')
}
}
const runAnalyzeMarket = async () => {
try {
await analyzeMarket()
} catch (error) {
logger.error(error, 'Error occurred while analyzing market:')
} finally {
setTimeout(runAnalyzeMarket, GET_MARKET_DATA_INTERVAL_SECONDS * 1000)
}
}
async function init() {
logger.level = LOG_LEVEL
logger.info(`
88888888888 8888888b. d8888 8888888b. 8888888 8888888888
888 888 Y88b d88888 888 Y88b 888 888
888 888 888 d88P888 888 888 888 888
888 888 d88P d88P 888 888 888 888 8888888
888 8888888P" d88P 888 888 888 888 888
888 888 T88b d88P 888 888 888 888 888
888 888 T88b d8888888888 888 .d88P 888 888
888 888 T88b d88P 888 8888888P" 8888888 8888888888
Solana ultimate trading bot. version: ${version}
`)
logger.info(`Stop Loss is ${STOP_LOSS}%.`)
logger.info(`Take Profit is ${TAKE_PROFIT}%.`)
logger.info(`Analyzing market price every ${GET_MARKET_DATA_INTERVAL_SECONDS} seconds.`)
logger.info(`Candle aggregate for ${CANDLE_AGGREGATE_MINUTES} min.`)
logger.info(`Slippage is ${SLIPPAGE_PERCENT}%.`)
logger.info(`Transaction priority fee is ${TRANSACTION_PRIORITY_FEE}.`)
try {
const assets = await getAssetsData()
buySymbol = assets.buySymbol
quoteAddress = assets.quoteAddress
logger.debug(`Quote Token Symbol: ${QUOTE_SYMBOL}. Found Address: ${quoteAddress}`)
} catch (error) {
logger.error(error, 'Error occurred while getting assets data')
process.exit(1)
}
await getBalances()
logger.info(`Start trading ${buySymbol}-${QUOTE_SYMBOL}.`)
try {
await loadSavedPosition()
if (activePosition) {
logger.info(`Saved position found. Balance: ${activePosition.amount} ${activePosition.buySymbol}. BuyPrice is ${activePosition.buyPrice} ${activePosition.quoteSymbol}.`)
}
} catch (error) {
logger.error(error, 'Error occurred while loading the saved position from file')
}
logger.info('———————————————————————')
}
async function analyzeMarket() {
const candleData = await getCandleData()
if (!candleData || !candleData.Data || !candleData.Data.Data || !candleData.Data.Data.length) {
if (candleData.Response === 'Error') {
throw new Error(`Failed to fetch candle data: ${candleData.Message}`)
} else {
throw new Error('Failed to fetch candle data or data is empty')
}
}
const data = candleData.Data.Data
const closePrice = data[data.length - 1].close
const emaShort = getEMA(data, 5)
const emaMedium = getEMA(data, 20)
const bb = getBB(data)
const rsi = getRSI(data)
logger.info(`Price: ${closePrice} ${QUOTE_SYMBOL}`)
logger.info(`EMA short: ${emaShort}`)
logger.info(`EMA medium: ${emaMedium}`)
logger.info(`BB lower: ${bb.lower}`)
logger.info(`BB upper: ${bb.upper}`)
logger.info(`RSI: ${rsi}`)
if (buyTokenBalance > 0) {
logger.debug(`Buy Token balance is ${buyTokenBalance} ${buySymbol}. Looking for sell signal...`)
if (activePosition) {
if (closePrice <= activePosition.buyPrice * (100 - STOP_LOSS) / 100) {
logger.warn(`Stop Loss is reached. Start selling...`)
await sell(closePrice)
}
if (closePrice >= activePosition.buyPrice * (100 + TAKE_PROFIT) / 100) {
logger.warn(`Take Profit is reached. Start selling...`)
await sell(closePrice)
}
}
if (((emaShort < emaMedium) || (closePrice > bb.upper)) && rsi >= RSI_TO_SELL) {
logger.warn(`SELL signal is detected. Start selling...`)
await sell(closePrice)
}
}
if (quoteTokenBalance > 0) {
logger.debug(`Quote Token balance is ${quoteTokenBalance} ${QUOTE_SYMBOL}. Looking for buy signal...`)
if (((emaShort > emaMedium) || (closePrice < bb.lower)) && rsi <= RSI_TO_BUY) {
logger.warn(`BUY signal is detected. Buying...`)
await buy(closePrice)
}
}
logger.info('———————————————————————')
}
async function sell(price: number) {
if (activePosition) {
logger.warn(`Price difference is ${price - activePosition.buyPrice} (${Math.sign(price - activePosition.buyPrice) * Math.round((activePosition.buyPrice / price) * 100 - 100) / 100}%)`)
}
await getBalances()
const amountWithDecimals = buyTokenBalance * (10 ** buyTokenDecimals)
try {
await buyToken(BUY_TOKEN_ADDRESS, quoteAddress, amountWithDecimals.toString(), logger)
} catch (error: any) {
if (error.err) {
logger.error(`Got error on sell transaction: ${error.err.message}`)
}
logger.error(error, `Got some error on sell transaction`)
return
}
logger.warn(`Sold ${buyTokenBalance} ${buySymbol}.`)
logger.info(`sleeping for 30s`)
await sleep(30000) // sleep for 15s / todo: make it nicer
await getBalances()
logger.warn(`Bought ${quoteTokenBalance} ${QUOTE_SYMBOL}. 1 ${buySymbol} = ${price} ${QUOTE_SYMBOL}`)
await clearSavedPosition()
}
async function buy(price: number) {
await getBalances()
const amountWithDecimals = quoteTokenBalance * (10 ** quoteTokenDecimals)
try {
await buyToken(quoteAddress, BUY_TOKEN_ADDRESS, amountWithDecimals.toString(), logger)
} catch (error: any) {
if (error.err) {
logger.error(`Got error on buy transaction: ${error.err.message}`)
}
logger.error(error, `Got some error on buy transaction`)
return
}
if (activePosition) {
logger.info('Previous active position found. Updating...')
}
logger.warn(`Sold ${quoteTokenBalance} ${QUOTE_SYMBOL}. For ${price} ${QUOTE_SYMBOL} per ${buySymbol}`)
logger.info(`sleeping for 30s`)
await sleep(30000) // sleep for 15s / todo: make it nicer
await getBalances()
logger.warn(`Bought ${buyTokenBalance} ${buySymbol}.`)
activePosition = {
buyPrice: activePosition ? (activePosition + price) / 2 : price,
amount: buyTokenBalance,
buySymbol: buySymbol,
quoteSymbol: QUOTE_SYMBOL
}
await savePosition()
}
async function getAssetDataByAddress(address: string): Promise<any> {
return await request(
'https://data-api.cryptocompare.com/onchain/v1/data/by/address?chain_symbol=SOL' +
'&address=' + address +
'&api_key=' + CRYPTO_COMPARE_API_KEY,
{})
}
async function getAssetDataByToken(token: string): Promise<any> {
return await request(
`https://price.jup.ag/v4/price?ids=${token}`,
{})
}
async function getCandleData(): Promise<any> {
return await request(
'https://min-api.cryptocompare.com/data/v2/histominute?limit=50' +
'&fsym=' + buySymbol +
'&tsym=' + QUOTE_SYMBOL +
'&aggregate=' + CANDLE_AGGREGATE_MINUTES,
{
method: 'GET',
headers: {'authorization': CRYPTO_COMPARE_API_KEY},
})
}
async function loadSavedPosition() {
if (fs.existsSync(positionFilePath)) {
const data = fs.readFileSync(positionFilePath, 'utf8')
activePosition = JSON.parse(data)
if (activePosition.buySymbol !== buySymbol || activePosition.quoteSymbol !== QUOTE_SYMBOL) {
logger.warn(`Previously saved pair is ${activePosition.buySymbol}-${activePosition.quoteSymbol}. But now trading ${buySymbol}-${QUOTE_SYMBOL}. Clearing saved position...`)
await clearSavedPosition()
}
logger.debug('Position loaded from file.')
} else {
logger.info('No previous position found. Starting fresh.')
}
}
async function savePosition() {
if (activePosition) {
const data = JSON.stringify(activePosition)
fs.writeFileSync(positionFilePath, data, 'utf8')
logger.debug(activePosition, 'Position file saved')
}
}
async function clearSavedPosition() {
activePosition = null
if (fs.existsSync(positionFilePath)) {
fs.unlinkSync(positionFilePath)
logger.debug('Position file was cleared.')
}
}
async function getAssetsData() {
const buyAssetData = await getAssetDataByAddress(BUY_TOKEN_ADDRESS)
if (buyAssetData?.Err?.message) {
throw new Error(buyAssetData.Err.message)
}
const buySymbol: string = buyAssetData?.Data?.SYMBOL
const quoteAssetData = await getAssetDataByToken(QUOTE_SYMBOL)
if (!Object.keys(quoteAssetData?.data?.[QUOTE_SYMBOL]).length) {
throw new Error(`Token ${QUOTE_SYMBOL} is not found.`)
}
const quoteAddress: string = quoteAssetData?.data[QUOTE_SYMBOL]?.id
return {buySymbol, quoteAddress}
}
async function getBalances() {
try {
logger.debug(`Getting balance amounts.`)
solBalance = await getSolBalance()
const buyTokenAmount = await getTokenAmountByAddress(BUY_TOKEN_ADDRESS, logger)
const quoteTokenAmount = await getTokenAmountByAddress(quoteAddress, logger)
buyTokenBalance = buyTokenAmount.amount / (10 ** buyTokenAmount.decimals)
buyTokenDecimals = buyTokenAmount.decimals
quoteTokenBalance = quoteTokenAmount.amount / (10 ** quoteTokenAmount.decimals)
quoteTokenDecimals = quoteTokenAmount.decimals
if (solBalance < 0.001) {
logger.error('Insufficient SOL balance. 0.001 SOL required to work properly.')
process.exit(1)
}
logger.info(`SOL Balance: ${solBalance} SOL`)
logger.info(`Token balance: ${buyTokenBalance} ${buySymbol} and ${quoteTokenBalance} ${QUOTE_SYMBOL}`)
} catch (error) {
logger.error(error, 'Error occurred while getting wallet balances')
process.exit(1)
}
}
main();