-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
191 lines (160 loc) · 5.65 KB
/
index.js
File metadata and controls
191 lines (160 loc) · 5.65 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
// 필요한 모듈을 import 합니다.
const Binance = require('binance-api-node').default;
const WebSocket = require('ws');
const blessed = require('blessed');
// API 키 및 시크릿키를 선언합니다.
const apiKey = 'your-api-key';
const apiSecret = 'your-api-secret';
// TradingBot의 상태를 표시할 텍스트 박스를 생성합니다.
const statusBox = blessed.box({
top: 'center',
left: 'center',
width: '50%',
height: '50%',
content: '',
tags: true,
border: {
type: 'line'
},
style: {
fg: 'white',
border: {
fg: '#f0f0f0'
}
}
});
// Dashboard에 텍스트 박스를 추가합니다.
dashboard.append(statusBox);
// TradingBot의 상태를 업데이트하는 함수입니다.
function updateStatus(status) {
statusBox.setContent(status);
dashboard.render();
}
// 현재 금액과 수익률을 표시할 텍스트 박스를 생성합니다.
const balanceBox = blessed.box({
top: '50%',
left: 'center',
width: '50%',
height: '50%',
content: '',
tags: true,
border: {
type: 'line'
},
style: {
fg: 'white',
border: {
fg: '#f0f0f0'
}
}
});
// Dashboard에 텍스트 박스를 추가합니다.
dashboard.append(balanceBox);
// 초기 투입금을 가져오는 함수입니다.
async function getInitialBalance() {
const accountInfo = await client.futuresAccount();
// 보유 중인 모든 자산의 총 가치를 계산합니다.
const balance = accountInfo.balances.reduce((sum, asset) => {
if (asset.asset !== 'USDT' && parseFloat(asset.walletBalance) > 0) {
const symbol = `${asset.asset}USDT`;
const ticker = client.futuresTicker(symbol);
const price = parseFloat(ticker.lastPrice);
sum += parseFloat(asset.walletBalance) * price;
} else if (asset.asset === 'USDT') {
sum += parseFloat(asset.walletBalance);
}
return sum;
}, 0);
return balance;
}
// 현재 금액과 수익률을 업데이트하는 함수입니다.
async function updateBalance() {
const positionRisk = await client.futures.positionRisk('BTCUSDT');
// 현재 금액을 계산합니다.
const currentBalance = parseFloat(positionRisk[0].marginBalance);
// 수익률을 계산합니다.
const profit = ((currentBalance - initialBalance) / initialBalance) * 100;
// 현재 금액과 수익률을 표시합니다.
const content = `Current Balance: ${currentBalance}\nProfit: ${profit}%\n`;
balanceBox.setContent(content);
dashboard.render();
}
// Binance Futures API와 WebSocket에 접속하기 위한 client를 생성합니다.
const client = Binance({
apiKey: apiKey,
apiSecret: apiSecret,
futures: true
});
const ws = new WebSocket('wss://fstream.binance.com/ws');
// 차트 데이터 배열을 선언합니다.
const candles = [];
// WebSocket으로 실시간으로 받아온 데이터를 차트 데이터 배열에 추가하는 함수입니다.
function subscribeToCandlestick(symbol, interval) {
const streamName = `${symbol.toLowerCase()}@kline_${interval}`;
ws.send(
JSON.stringify({
method: 'SUBSCRIBE',
params: [streamName],
id: 1
})
);
ws.on('message', (data) => {
const parsedData = JSON.parse(data);
// WebSocket으로 받아온 데이터를 차트 데이터 배열에 추가합니다.
const candleData = parsedData.k;
candles.push({
time: candleData.t,
open: parseFloat(candleData.o),
high: parseFloat(candleData.h),
low: parseFloat(candleData.l),
close: parseFloat(candleData.c),
volume: parseFloat(candleData.v),
trades: parseInt(candleData.n)
});
// 최대 길이를 50으로 제한합니다.
if (candles.length > 50) {
candles.shift();
}
});
}
// RSI 거래 전략을 구현한 TradingBot 로직입니다.
async function tradingBotLogic() {
// 지난 14개의 캔들 데이터를 추출합니다.
const closePrices = candles.slice(-14).map((candle) => parseFloat(candle.close));
// RSI 값을 계산합니다.
const rsi = talib.RSI(closePrices, 14)[13];
// TradingBot의 상태를 업데이트합니다.
const status = `RSI: ${rsi}\n`;
updateStatus(status);
// RSI 값에 따라 매수/매도 시그널을 결정합니다.
if (rsi < 30) {
// RSI 값이 30 이하인 경우 매수합니다.
console.log('Buy signal detected! Placing order...');
const order = await client.futures.marketBuy('BTCUSDT', 0.01);
console.log('Order executed:', order);
// TradingBot의 상태를 업데이트합니다.
const status = `RSI: ${rsi}\nBuy signal detected! Order executed: ${order.orderId}\n`;
updateStatus(status);
} else if (rsi > 70) {
// RSI 값이 70 이상인 경우 매도합니다.
console.log('Sell signal detected! Placing order...');
const order = await client.futures.marketSell('BTCUSDT', 0.01);
console.log('Order executed:', order);
// TradingBot의 상태를 업데이트합니다.
const status = `RSI: ${rsi}\nSell signal detected! Order executed: ${order.orderId}\n`;
updateStatus(status);
}
}
const initialBalance = await getInitialBalance();
// TradingBot을 실행하는 함수입니다.
function runTradingBot() {
// WebSocket을 통해 실시간으로 차트 데이터를 받아옵니다.
subscribeToCandlestick('BTCUSDT', '1m');
// 일정 시간 간격으로 TradingBot 로직을 실행합니다.
setInterval(async () => {
await tradingBotLogic();
await updateBalance();
}, 10000);
}
// TradingBot을 실행합니다.
runTradingBot();