Automated Trading Bot Design and Impleme
Automated Trading Bot Design and Impleme
Abdallah M. Shnaino
Department Software Development, Islamic University of Gaza, Palestine,
[email protected]
Abstract—This project addresses the limitations of traditional methods of
placing orders on cryptocurrency platforms. With a sophisticated bot and an innovative
website, customers can make transactions easily and efficiently at any time and from
anywhere. The solution makes use of the latest technology to automate the trading
process, saving time and enabling clients to take advantage of market volatility. The
website provides an easy-to-use interface, real-time market data, and customized
trading preferences. Security is prioritized through strong encryption protocols and
multiple layers of security. The project aims to revolutionize digital currency trading,
and enable individuals to achieve financial success by automating the trading process.
Keywords: Agile; Cryptocurrency; Fintech; Automation; Multithreading.
Introduction
This paper proposes the automation of cryptocurrency trading through the
development of a bot that utilizes real-time market analysis and a collection of
strategies to execute buy, sell, and hold actions on a chosen platform, such as Binance.
The primary aim is to enhance user well-being by employing an event-driven
architecture to interconnect and share data in the business workflow from preferred
platforms until the chosen strategy is executed.
Acknowledging the necessity for a non-manual trading system, the paper
implements a web-based application where users can create their own bots, select
specific strategies, and define indicators for the bots to work on. The trading process
runs from start to finish or until cancellation without requiring users to be constantly
in front of the trading screen.
The primary objective of this paper is to demonstrate the effectiveness and
necessity of automated trading processes.
Our solution revolves around the incorporation of a sophisticated trading bot and
a user-friendly website interface. Each bot is distinguished according to the strategy it
uses, some of which use Relative Strength Index (RSI) and others that use Exponential
47
Moving Average (EMA) or even a customized strategy RSI as strategy binance as
trading platform. In our project, we employed XP as our chosen agile methodology.
I. Methodology
Requirements
Requirements and specifications the main objective of this project is to create an
automated trading process, enabling users to trade without the constant need to be in
front of the trading screen. Users will input specific parameters, such as the type of
strategy and its corresponding values, into the bot. The bot will then execute trades
based on these values until the pre-defined conditions for buying and selling are met.
To accomplish this, a seamless connection between the trading platform (e.g., Binance),
TradingView for pre-defined indicators, and our system is crucial. Additionally, the
system must address non-functional requirements, including ensuring robustness,
security, and efficiency in the automated trading process.
Design
Database design
In the given database design, there are two main entities: User and Strategy. The
User entity represents individuals who can create their own User entity by providing
their full name, custom password, Binance API (Application Programming Interface)
key, and secret key. With their user entity, users gain access to various operations
associated with the Binance platform. The Strategy entity allows users to create, update,
48
and cancel individual bots for their trading strategies. Each Strategy entity contains
specific data related to the strategy it represents.
To summarize:
• The User entity stores user information, including their full name, custom
password, and Binance API keys.
• Users can perform operations associated with Binance using their user
entity.
• The Strategy entity enables users to create, update, and cancel trading bots.
• Each Strategy entity holds data specific to the corresponding trading
strategy.
This database design facilitates the management of user information, Binance
API access, and trading strategy entities, enabling users to effectively create, update,
and cancel their trading bots as per their requirements.
1) Software Architecture
49
By adopting the MVC pattern, we have achieved separation of concerns,
allowing for better code organization, modularity, and maintainability. The Model
encapsulates the data and core functionality, ensuring data integrity and consistency.
The View focuses on rendering the user interface, providing an intuitive and visually
appealing experience. The Controller coordinates the communication between the
Model and View, facilitating user interactions and business logic execution.
This architecture has facilitated collaboration among team members, as different
components can be developed independently and integrated seamlessly. It has also
enhanced the scalability of our system, enabling easy modification or expansion of
specific components without affecting the entire application.
Overall, the utilization of the MVC pattern in our development process has
significantly contributed to the efficiency, flexibility, and robustness of our software
solution.
50
Our system operates simultaneously with Binance for executing trading
operations and with TradingView for analyzing the market using real-time data.
51
encompassing elements such as trading pairs, trade amounts, stop loss, and take profit
parameters.
const {
keys,
strategyId,
} = workerData;
let binanceClient = initClient(keys.binanceAPIKey, keys.binanceSecretKey)
let strategy = await findStrategyById(strategyId)
let userId = strategy.dataValues.userId
let strategyData = JSON.parse(strategy.strategyData)
let numberOfTrades = strategyData.numberOfTrades;
async function startRsi(strategyData, strategyId, updateStrategy) {
try {
let pairs = strategyData.pairs
for (let pair of pairs) {
const {
input
} = await getDetachSourceFromOHLCV('binance', pair, strategyData.timeFrame, false) // true if you
want to get future market
var atrData = await rsi(strategyData.period, strategyData.inputSource, input)
let rsiValue = Number.parseInt(atrData[atrData.length - 1]);
let payingIndicators = strategyData.payingIndicators
for (let signal of payingIndicators) {
const isAccepted = await isAcceptedTransaction(binanceClient,
strategyData.ammount, pair)
if (rsiValue == signal && isAccepted) {
}
if (numberOfTrades <= 0 && monetor.length == 0) {
parentPort.postMessage({
message: "operation done"
})
clearInterval(interval);
}
}
}
}
} catch (error) {
parentPort.postMessage(error)
}
}
let interval = setInterval(startRsi, 5000, strategyData, strategyId, updateStrategy)
parentPort.on('message', async (data) => {
strategy = await findStrategyById(strategyId)
strategyData = JSON.parse(strategy.strategyData)
clearInterval(interval);
interval = setInterval(startRsi, 5000, strategyData, strategyId)
parentPort.postMessage('Hello from the worker thread!');
});
}
54
Functions Assisting the RSI Bot
async function getCurrentPrice(binanceClient, pair) {
let symbol = pair.split("/").join("")
let symblePrice = await binanceClient.prices({
symbol
})
return symblePrice
}
function financial(x) {
return Number.parseFloat(x).toFixed(1);
}
56
Trading Bot
Main Settings: In the Main Settings section, users can configure the bot and
select the platform on which the bot will operate.
Currencies: Users have the ability to specify the currencies in which the bot will
engage in trading.
Trading Strategy: Users can define the maximum number of open trades and
set the purchase amount for each order, thereby establishing their preferred trading
strategy.
Selected Strategy: Users can choose the specific strategy they wish to
implement for their trading activities.
Targeted Profits: Users have control over determining the desired percentage
increase in currency value, at which point the bot will execute profit-taking actions.
This feature also offers two options for selecting the profit-taking method.
Price Average Calculation: The system calculates the percentage increase in
currency value based on the average pricing of the product.
Stop Loss: Users can set the currency rate at which the stop loss mechanism will
be triggered to safeguard against potential losses in a trade.
Settings Page
Settings Page: The Settings page serves as a versatile platform for users to
allocate and control various aspects of their accounts. It offers a wide range of
customization options, empowering users to personalize their experience according to
their unique preferences. On this page, users can easily manage notifications, update
their profile information, adjust privacy settings, and access other configurable options.
The Settings page ensures that users have full control over their accounts, enabling them
to tailor their browsing experience and optimize their interactions with the platform.
Testing
Test-Driven Development
With TDD (Test-Driven Development), before writing implementation code, the
developer writes automated unit test cases for the new functionality they are about to
57
implement. After writing test cases that generally will not even compile, the developers
write implementation code to pass these test cases. The developer writes a few test
cases, implements the code, writes a few test cases, implements the code, and so on [4].
The work is kept within the developer’s intellectual control because he or she is
continuously making small design and implementation decisions and increasing
functionality at a relatively consistent rate. New functionality is not considered properly
implemented unless these new unit test cases and every other unit test case written for
the code base run properly.
For example, we want to create a bot that uses Relative Strength Index (RSI)
strategy so we should ensure that our bot.
accurately represents a set of orders using the trading platform chosen by the
user.
Unit Testing for RSI Bot Functions and Worker Threads
Jest was utilized as the unit testing framework to create the unit tests. Each test
case is written using the Jest syntax and follows the Arrange-Act-Assert pattern to set
up the test scenario, perform the necessary actions, and verify the expected outcomes.
Fig. 8 show sample of test code.
const {
runRsiIndecator,
getCurrentPrice,
computeWinningMarginPercent,
computelosingMarginPercent,
financial
} = require('./path-to-your-file'); // Replace with the actual path
describe('computeWinningMarginPercent', () => {
it('should calculate the final price with winning margin', () => {
const price = 100;
const winningMarginPercent = 0.05;
const result = computeWinningMarginPercent(price, winningMarginPercent);
expect(result).toEqual(105);
58
});
});
describe('computelosingMarginPercent', () => {
it('should calculate the final price with losing margin', () => {
const price = 100;
const losingMarginPercent = 0.1;
const result = computelosingMarginPercent(price, losingMarginPercent);
expect(result).toEqual(90);
});
});
describe('financial', () => {
it('should format a number to have one decimal point', () => {
const number = 123.456;
const result = financial(number);
expect(result).toEqual('123.5');
});
});
});
Conclusion
We have developed a bot-powered cryptocurrency trading platform. Its purpose
is to enable simultaneous and diversified cryptocurrency trading. Following the Agile
methodology.
We constructed the application through the following steps:
• Collecting requirements
• Designing
• Building
• Testing
• Deploying
• Reviewing
Our system uses case diagrams, use case tables, and sequence diagrams of system
functions.
For system design, we created the ER diagram and user interface design. In the
implementation and testing phase, we provided a detailed explanation of the
implementation process and thoroughly tested the site's key functionalities. The
resulting site features a subscriber interface that allows users to register, initiate trades,
and select preferred currencies for trading.
59
References
[1] "Medium" [Online]. Available: https://medium.com/@syantien/introduction-
to-model-view-controller-mvc-pattern-8cbc693f043.
[2] J. Welles Wilder Jr. "New Concepts in Technical Trading Systems." Trend
Research, 1978.
[3] "Investopedia" [Online]. Available:
https://www.investopedia.com/terms/r/rsi.asp#citation-2.
[4] A. Shadi and P. Dennis, "Using Test Oracles and Formal Specifications with
Test-Driven Development", International Journal of Software Engineering and
Knowledge Engineering, July 2013, doi: 10.1142/S0218194013500113
60