-
-
Save BransonGitomeh/367436f77c3237cd5c8909eb8c3f4685 to your computer and use it in GitHub Desktop.
BINANCE_API_KEY= | |
BINANCE_SECRET_KEY= | |
BINANCE_API_URL=https://fapi.binance.com |
require('dotenv').config(); | |
const axios = require('axios'); | |
const Binance = require('node-binance-api'); | |
// Extract necessary variables from environment | |
const { BINANCE_API_KEY, BINANCE_SECRET_KEY, NATS_URL } = process.env; | |
// Initialize Binance API client with authentication | |
const binance = new Binance().options({ | |
APIKEY: BINANCE_API_KEY, | |
APISECRET: BINANCE_SECRET_KEY, | |
useServerTime: true, | |
recvWindow: 5000, | |
}); | |
// Set binance object as global variable | |
global.binance = binance; | |
const assetInfoCache = {}; | |
const getAssetInfo = async function (symbol) { | |
// Check if the response is already cached | |
if (assetInfoCache[symbol]) { | |
return Promise.resolve(assetInfoCache[symbol]); | |
} | |
try { | |
const response = await axios({ | |
method: 'GET', | |
url: 'https://fapi.binance.com/fapi/v1/exchangeInfo', | |
}); | |
const { symbols } = response.data; | |
const symbolInfo = symbols.find(s => s.symbol === symbol); | |
const { notional } = symbolInfo.filters.find(filter => { | |
return filter.filterType == 'MIN_NOTIONAL' | |
}) | |
if (!symbolInfo.baseAssetPrecision) { | |
logger.info(symbolInfo); | |
} | |
// Store the response in the cache | |
assetInfoCache[symbol] = { | |
basePrecision: symbolInfo.baseAssetPrecision, | |
quotePrecision: symbolInfo.quotePrecision, | |
minNotional: Number(notional) | |
}; | |
return Promise.resolve(assetInfoCache[symbol]); | |
} catch (error) { | |
console.error(`Error getting asset info: ${error}`); | |
throw error; | |
} | |
} | |
async function getCurrentPrice(symbol) { | |
return new Promise(async (resolve, reject) => { | |
try { | |
binance.futuresTickerStream(symbol, ticker => { | |
const currentPrice = parseFloat(ticker.close); | |
resolve(currentPrice) | |
}); | |
} catch (error) { | |
console.error(`Error getting current price for symbol ${symbol}: ${error.message}`); | |
throw error; | |
} | |
}) | |
} | |
const openOrder = async (symbol) => { | |
const assetInfo = await getAssetInfo(symbol); | |
const { basePrecision, quotePrecision, minNotional } = assetInfo; | |
const { availableBalance } = await global.binance.futuresAccount(); | |
const riskPercentage = 0.2; // Risk 30% of available balance | |
const riskAmount = minNotional//availableBalance * riskPercentage; // Example risk amount | |
const leverage = 20; // Example leverage | |
const currentPrice = await getCurrentPrice(symbol) | |
let positionSize = Math.ceil(riskAmount / currentPrice); | |
const response = await global.binance.futuresSell(symbol, positionSize, undefined, { | |
leverage | |
}); | |
return response | |
} | |
const reverseFailingPosition = async (position) => { | |
const { symbol } = position | |
const assetInfo = await getAssetInfo(symbol); | |
const { basePrecision, quotePrecision, minNotional } = assetInfo; | |
const { availableBalance } = await global.binance.futuresAccount(); | |
const riskPercentage = 0.2; // Risk 30% of available balance | |
const riskAmount = minNotional//availableBalance * riskPercentage; // Example risk amount | |
const leverage = 20; // Example leverage | |
const currentPrice = await getCurrentPrice(symbol) | |
let positionSize = Math.ceil(riskAmount / currentPrice); | |
let response; | |
if (Number(position.positionAmt) > 0) { | |
response = await global.binance.futuresSell(symbol, positionSize * 2, undefined, { | |
leverage | |
}); | |
} else { | |
response = await global.binance.futuresBuy(symbol, positionSize * 2, undefined, { | |
leverage | |
}); | |
} | |
return response | |
} | |
const symbols = [ | |
"IMXUSDT", | |
"XRPUSDT", | |
// "ETHUSDT", | |
// "BTCUSDT", | |
"DOGEUSDT", | |
"BALUSDT", | |
"EOSUSDT", | |
// "ETCUSDT", | |
"BATUSDT", | |
"BELUSDT", | |
// "BNBUSDT" | |
]; | |
async function openOrdersSequentially(openPositions) { | |
for (const symbol of symbols) { | |
if (!openPositions.includes(symbol)) { | |
const response = await openOrder(symbol); | |
console.log(`Order for ${symbol}: ${JSON.stringify(response)}`); | |
} | |
} | |
} | |
function calculateROE(position) { | |
const entryPrice = parseFloat(position.entryPrice); | |
const markPrice = parseFloat(position.markPrice); | |
const positionAmt = parseFloat(position.positionAmt); | |
const leverage = parseFloat(position.leverage); | |
const unRealizedProfit = parseFloat(position.unRealizedProfit); | |
// Calculate the current value of the position | |
const currentValue = positionAmt * markPrice; | |
// Calculate the initial margin required for the position | |
const initialMargin = currentValue / leverage; | |
// Calculate the unrealized PnL of the position | |
const unrealizedPnl = parseFloat(position.unRealizedProfit); | |
// Calculate the return on equity (ROE) | |
const ROE = ((unrealizedPnl / initialMargin) * 100).toFixed(2); | |
if (unRealizedProfit > 0) | |
return Math.abs(ROE); | |
return -Math.abs(ROE); | |
} | |
const start = async () => { | |
const { serverTime: timestamp } = await binance.time(); | |
const binanceGeneralPositions = await global.binance.futuresPositionRisk({ timestamp }) || []; | |
if (!binanceGeneralPositions[0]) { | |
console.error("Could not get access to Latest Positions data from binance.futuresPositionRisk") | |
return; | |
} | |
const openPositions = binanceGeneralPositions.filter(position => { | |
return Number(position.positionAmt) !== 0 | |
}) | |
const openPositionsSymbols = openPositions.map(position => position.symbol) | |
await openOrdersSequentially(openPositionsSymbols); | |
const positionData = [] | |
for (const position of openPositions) { | |
try { | |
const binanceGeneralPositions = await global.binance.futuresPositionRisk({ timestamp }) || []; | |
const positionToMonitor = binanceGeneralPositions.find(generalPos => generalPos.symbol === position.symbol) | |
const ROE = await calculateROE(positionToMonitor) | |
const { symbol, unRealizedProfit, leverage } = position | |
positionData.push({ | |
symbol, | |
uPNL: Number(unRealizedProfit).toFixed(2), | |
uPNLKes: Number(Number(unRealizedProfit) * 131).toFixed(2), | |
ROE, | |
leverage | |
}) | |
if (ROE < -10) { | |
const attemptToFlipResponse = await reverseFailingPosition(positionToMonitor) | |
console.log("Successfully flipped position ", attemptToFlipResponse) | |
console.table(positionToMonitor) | |
} | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
const sortedPositionData = positionData.sort((a, b) => a.ROE - b.ROE) | |
console.table(sortedPositionData) | |
start().catch(console.log) | |
} | |
start().catch(console.log) |
Trading Bot for Managing Futures Positions
This trading bot is designed to automate the process of opening and managing futures trading positions on the Binance Futures platform. The bot allows you to gain from both rising and falling markets by utilizing futures contracts.
What are Futures Contracts?
Futures contracts are derivative financial instruments that allow traders to speculate on the future price movements of an underlying asset, such as cryptocurrencies. These contracts enable traders to profit from both upward and downward price trends by taking long (buy) or short (sell) positions.
Unlike spot trading, where you directly own the underlying asset, futures trading involves trading contracts that represent an agreement to buy or sell the asset at a predetermined price and date in the future. This allows traders to gain exposure to the asset's price movements without actually owning it.
How Does the Bot Help with Portfolio Management?
This trading bot automates the process of managing your futures trading positions, ensuring that your positions remain above a predefined threshold of -10% return on equity (ROE). It provides the following benefits:
-
Automated Position Opening: The bot opens new futures trading positions based on a predefined list of symbols. You can configure the list of symbols and other parameters to align with your trading strategy.
-
ROE Monitoring: The bot continuously monitors the ROE of your open positions. It calculates the ROE based on the unrealized profit, entry price, mark price, position amount, and leverage. This monitoring helps you stay updated on the performance of your positions.
-
Position Flipping: If the ROE of a position falls below the -10% threshold, the bot automatically flips the position. It closes the current position and opens a new position in the opposite direction. This strategy aims to minimize losses and take advantage of potential market reversals.
-
Risk Management: The bot incorporates risk management techniques by considering the available balance and risk percentage. It calculates the risk amount for each position based on your predefined risk percentage. This helps you manage your exposure and control the amount of capital at risk.
-
Asset Information Retrieval: The bot retrieves essential asset information, including base precision, quote precision, and minimum notional value, for the symbols you are trading. This information assists in making informed trading decisions and ensures compliance with Binance's trading requirements.
-
Easy Setup and Customization: The bot is designed to be easy to set up and customize. You need to provide your Binance Futures API credentials and adjust the trading parameters according to your preferences. Once configured, you can run the bot, and it will handle the trading operations automatically.
Example Actions from an Empty Portfolio to Position Flipping
Let's walk through an example to illustrate how the bot automates the tasks and manages your portfolio:
-
You set up the bot by installing the required dependencies, configuring the API credentials, and adjusting the trading parameters such as symbols, risk percentage, and leverage.
-
You run the bot, and it initializes by retrieving the current timestamp and fetching the open positions (which will be empty at the beginning).
-
The bot sequentially opens new futures trading positions for the symbols you specified. It calculates the risk amount based on the available balance and risk percentage. The positions are opened with the defined leverage.
-
The bot continuously monitors the ROE of the open positions. It calculates the ROE based on the unrealized profit, entry price, mark price, position amount, and leverage. If the ROE of any position drops below -10%, the bot takes action to flip the position.
-
Suppose one of the positions reaches an ROE below -10%. The bot closes the current position and opens a new position in the opposite direction. It calculates the position size based on the risk amount and the current price.
-
The bot displays the position data, including the symbol, unrealized profit, ROE, and leverage. It sorts the positions based on ROE in ascending order, allowing you to quickly identify the positions that require attention.
-
The bot continues to monitor the positions, automatically flipping any position that falls below the -10% threshold. It provides real-time updates on the position data, helping you keep track of the performance and manage your portfolio effectively.
By automating these tasks, the trading bot simplifies the process of managing your futures trading positions and enables you to gain from both upward and downward market trends.
Prerequisites, Installation, and Usage
Please refer to the Installation and Usage sections in the previous README for detailed instructions on setting up and running the trading bot.
Disclaimer
- This trading bot is provided for educational and informational purposes only. Use it at your own risk.
- Make sure to thoroughly test and understand the bot's behavior in a simulated environment before using it with real funds.
- Trading in futures markets involves risks and can result in financial losses. Be cautious and trade responsibly.
Contributing
Contributions to enhance and improve this trading bot are welcome. If you find any issues or have ideas for new features, please open an issue or submit a pull request on the GitHub repository.
License
This trading bot is licensed under the MIT License.
Why Focus on Futures Contracts?
Futures contracts offer unique advantages that make them an attractive choice for maximizing returns:
-
Profit from Rising and Falling Markets: Unlike spot trading, futures contracts enable traders to profit from both upward and downward price movements. By taking long (buy) or short (sell) positions, the bot allows you to capitalize on opportunities in any market direction.
-
Leverage for Enhanced Returns: Binance Futures provides leverage, allowing traders to amplify their returns. By utilizing maximum leverage, the bot enables you to potentially achieve significant increases in return on equity (ROE) and capture opportunities for higher gains.
-
Minimum Positions and Risk Management: The bot incorporates the minimum position sizes enforced by Binance to ensure the lowest risk exposure per trade. This risk management approach protects against excessive losses and helps you maintain a balanced portfolio.
-. By leveraging the maximum available leverage, the bot aims to achieve amplified gains. The use of leverage allows you to potentially achieve ROEs of up to 1000%, which would be challenging and time-consuming to open manually.
-. The bot displays the position data, including the symbol, unrealized profit, ROE, and leverage. It sorts the positions based on ROE in ascending order, allowing you to quickly identify the positions that require attention and potential flipping.
-. The bot continues to monitor the positions, automatically flipping any position that falls below the -10% threshold. It provides real-time updates on the position data, helping you keep track of the performance and manage your portfolio effectively.
With the trading bot automating these tasks and utilizing futures contracts, you can easily get started with crypto portfolio management, maximize your returns, and effectively manage risk.
currently logs look like this
and the configurations of which markets to operate on can be changed in the code here
const symbols = [
"IMXUSDT",
"XRPUSDT",
// "ETHUSDT",
// "BTCUSDT",
"DOGEUSDT",
"BALUSDT",
"EOSUSDT",
// "ETCUSDT",
"BATUSDT",
"BELUSDT",
// "BNBUSDT"
];
Trading Bot for Managing Futures Positions
This trading bot is designed to automate the process of opening and managing futures trading positions on the Binance Futures platform. The bot focuses on ensuring that the positions remain above a threshold of -10% return on equity (ROE).
Features
Prerequisites
To use this trading bot, you need to have the following:
Installation
Clone the repository:
Navigate to the project directory:
cd trading-bot
Install the dependencies:
Set up the environment variables:
Create a
.env
file in the project directory.Add the following lines to the
.env
file and replace the placeholders with your actual API credentials:Customize the trading parameters:
index.js
file in a text editor.symbols
array to include the symbols you want to trade.Usage
Run the bot:
The bot will automatically open futures trading positions for the specified symbols if they are not already open.
It will continuously monitor the ROE of open positions.
If the ROE of a position drops below -10%, the bot will close the position and open a new position in the opposite direction.
The bot will display the position data, including the symbol, unrealized profit, ROE, and leverage.
The positions will be sorted based on ROE in ascending order.
Configuration
You can customize the bot's behavior by modifying the following parameters in the
index.js
file:Disclaimer
Contributing
Contributions to enhance and improve this trading bot are welcome. If you find any issues or have
ideas for new features, please open an issue or submit a pull request on the GitHub repository.
License
This trading bot is licensed under the MIT License.