-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
81 lines (66 loc) · 2.75 KB
/
app.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
import express from 'express'
import { createExchange } from '@compendiumfi/pendax/exchanges/exchange.js'
// This Code Needs Further Review And Testing. Please Use With Caution
const app = express();
app.use(express.json());
// Initialize the MEXC exchange object using PENDAX SDK
const mexcClient = createExchange({
exchange: "mexc",
authenticate: true,
key: process.env.MEXC_KEY,
secret: process.env.MEXC_SECRET
// Add other necessary authentication details
});
app.post('/webhook', async (req, res) => {
const { signal, symbol, quantity } = req.body;
try {
const result = await processTradeSignal(signal, symbol, quantity);
res.status(200).send(result);
} catch (error) {
console.error(`Error processing trade signal: ${error.message}`);
res.status(500).send({ message: error.message });
}
});
async function processTradeSignal(signal, symbol, quantity) {
try {
// Validate and format the input
if (!['buy', 'sell'].includes(signal.toLowerCase())) {
throw new Error("Invalid signal. Signal must be 'buy' or 'sell'.");
}
if (isNaN(quantity) || quantity < 1 || quantity > 100) {
throw new Error("Invalid quantity. Quantity must be an integer between 1 and 100.");
}
const accountInfo = await mexcClient.getSpotAccountInfo();
const tradeSize = calculateTradeSize(accountInfo, symbol, signal.toUpperCase(), quantity);
await mexcClient.newOrderSpot({
symbol: symbol.replace('-', ''),
side: signal.toUpperCase(),
type: 'market',
quantity: tradeSize
});
return `Order placed: ${signal.toUpperCase()} ${tradeSize} in market ${symbol.replace('-', '')}`;
} catch (error) {
throw error;
}
}
function calculateTradeSize(accountInfo, symbol, side, quantityPct) {
// Split the symbol at '-' to get base and quote assets
const [baseAsset, quoteAsset] = symbol.split('-');
let asset;
if (side === 'BUY') {
// For BUY orders, use the quote currency (e.g., USDT in MANGO-USDT)
asset = quoteAsset;
} else {
// For SELL orders, use the base currency (e.g., MANGO in MANGO-USDT)
asset = baseAsset;
}
const balance = accountInfo.balances?.find(b => b.asset === asset);
if (!balance || parseFloat(balance.free) <= 0) {
throw new Error(`Insufficient ${asset} balance`);
}
// Calculate the trade size as a percentage of the available balance
const size = (parseFloat(balance.free) * quantityPct) / 100;
return size.toFixed(8); // Assuming 8 decimal places, adjust as needed for MEXC
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));