Hey Devs and possibly traders,
In my college, I created a side-project that trades in cryptocurrencies with real money. So, I can make some profits and more importantly save myself from losses while sleeping.
It started like most side projects β I was bored, curious, and had just enough caffeine to believe I could beat the crypto market (spoiler: I couldn't, but it was worth it).
Let's start with the "BACKGROUND" first.
Background
At that time crypto was becoming mainstream and I was also fantisized by the wave of crypto currency. A decentralized network, sharing tokens without any third party, a mined block, and obviously a 10x or sometimes 1000x profits. ($ in eyes emoji).
So, I thought why not start trading in crypto. I created my account on CoinDCX and started trading with my first 500 ruppee.
After some time, I realized I was looking at the charts too often and everytime I get 10 min, between my classes, during lunch break, while traveling to and from college. And since I have a developer mindset, my dev instincts kick in. Why not automate this process? Can I make a script to do all that for me?
This small question lead me to creating my Crypto.trader() project. But I can't give you the exact code as it got deleted when my hard disk once crashed a few years back.
Nah, I am not building it in this blog, and even now that I think of building it, there's a whole lot of taxes on crypto and stuff. But, my dev instincts still want to create something like that again. Well, another story for another day.
By this blog, I just want to write down my experience of how a simple idea lead me to building a full-fledged project, and might be possible that someone's dev instincts kick in by reading this article leading to a new solution.
So, I digged in, did some research and found that coindcx has developer API, from which you can place order, get market details of a token like current price, cancel an order, get status of the order and much more.
Now my idea has a ground, let's create a script/bot that will run 24/7 and monitor the different currencies and get the market data, run some calculation, either place the order and after making profits sell it or hold it.
Back then, I did not understand the design diagrams and design patters, so I just created what I like.
Okay, Enough chit-chat. Let's get started
βοΈ My Very Own Crypto Bot: Overview
The idea was to build a 24/7 script/bot that:
- Monitors market data of multiple currencies.
- Runs some calculations using a tiny brain (i.e., an algorithm).
- Makes a decision: buy, sell, or hold.
- Places the order if needed, and logs everything and notify me like my well-wisher.
π§± Architecture: Four Simple Python Classes
Portfolio
Handles everything market-related:
- Fetches the current price of a token.
- Places buy/sell orders.
- Tracks wallet balance.
- Maintains what tokens we hold.
Basically, itβs the botβs bank account + market window.
Trader
This is where the magic (or nonsense?) happens:
- Contains the algorithm that decides whether we should buy, sell, or hold.
- Core logic lives in a method called decide_buy_sell_hold()
Logger
If it logs, it's real:
- Writes all decisions and actions into a log.txt file. (Buy/Sell signal, at what time, at what price, for which token, etc.)
- Sends alerts when an order is placed or an asset is bought/sold.
Crypto
This is the main orchestrator class.
It combines Portfolio, Trader, and Logger together and kicks off the loop.
Main class that packs all of these classes is called Crypto, hence I named it Crypto.trader(), because why not β letβs pretend Python has namespaces like Java.
Yes, you heard it right, I used python language to fuel up my idea.
π Technology Stack
Language: Python (because of course)
API: CoinDCX Developer API, Twilio for messaging
Data Storage: Flat file logging (log.txt)
Runtime: A loop that sleeps between API calls and keeps the bot running 24/7
Deployment: Amazon EC2 instance
πΈ The five senses of the Bot: Portfolio API's
This class deals with all kind of marketplace related things
- Getting information about the token/coin
- Placing/Revoking a market place order (BUY/SELL)
- Polling on the pending order to mark if fulfilled or rejected.
- If order is fulfilled, add it to the available to sell funds list and if the order is not fulfilled for 10 min, cancel the order and add the funds back into available funds.
- Fetches the available balance from the wallet.
This class manages all the configs and available funds, so the Trader class can make an informed decision.
Whenever algo generates a buy/sell signal, the Portfolio class creates a corresponding BUY/SELL order, and put a watcher on it, that polls the order every 10 seconds to know if the order is fulfilled or rejected.
If the order if fulfilled, add the token/coin into the bought list so it can later sell it, when feasible.
If the order is not fulfilled for 10 min, cancels the order and add the funds back to the available funds so it can be used for buying a token later.
π§ The Brain of the Bot: Trader Logic
The main logic of this bot relies in the Trader class, the trader class has a method decide_buy_sell_hold, which when called upon with params, return whether we want to hold the asset, buy it (if yes, at what price) or sell it if we already bought (if yes, at what price).
π Step-by-Step Process:
Step 1 Receive Token: The method is called with the token name (e.g., BTC-INR).
Step 2 Get Price History:
- Pulls the last n prices (default 5) of the token.
- Used to spot trends.
Step 3 Check If Can Sell:
- Looks at Portfolio holdings.
- Already holding this token? Okay, maybe we can sell or hold.
Step 4 Sell Conditions:
If prices are strictly decreasing β look deeper:
- If current loss > 5%, sell (stop-loss).
- If current profit > 20%, sell (profit booking).
Step 5 Check If Can Buy:
- Looks into the Portfolio wallet.
- Enough balance? Okay, maybe we can buy.
Step 6 Buy Conditions:
- If the last 5 prices are strictly increasing (bullish trend).
- AND we have money β return BUY signal with price.
Step 7 Else:
- No condition matched β return null (HOLD).
π¦Ύ Treasurer and Notifier: Logger
The main objective of this class is to log everything in txt files so there is a written log of everything happened, why it happened and if the bot needs to restart itself, it knows what it already has in account and when it bought it at what price so it can take right decisions.
Logging Mechanism
Whenever algo generate buy or sell signal, timestamp, when the market order is placed, when it got fulfilled or rejected, what was the market depth when the decision was generated, and more. It writes everything down in txt files.
algo_logs.txt
One txt file is to log all of the decisions that algo takes and parameters that made that decision possible.
portfolio_summary.txt
And One txt file is to maintain the config, what currencies to trade in, current order statuses, available funds, what we have in portfolio, when we bought at and at which price point. All the data that the bot can read again if it restarted so it knows what it was doing, funds, and other things. This helps, when I want to change some code or something so the process needs to be restarted.
Notifications
As for the notification part, I used Twilio's API for sending whatsapp messages to myself whenever the bot buys, or sells and at what price. Just to loop myself in and to know if I'm broke or not.
Twilio provides a way so you can send whatsapp messages to any number, so I integrated it to send me a notification when the buy/sell order is placed and when an order gets fulfilled or rejected.
β Deployment
Since I need to run this script 24*7, I chose Amazon's EC2 instance, the basic and Free for 1 yr plan. I uploaded my code directly on the instance, setup the configs, and ran the script hoping I would not go bankrupt.
π° Finally, let's count the money
Time for the results, we all are waiting for.
I ran the script first time with real money and let it run for one night.
In one night, it made 18Rs. profit. I know it wasn't enough but hey it was just testing.
So, I tuned in some more parameters and let it run for one full day. It made 84.6 rs profit on that day.
After this, I found that if created an order but since the service restarted, it never pulled the status and it never counted it as bought. Here goes, my 342 rs.
I fixed the bug and ran the script again with a max limit on one order of 100 rs. just to keep myself safe from huge losses.
After all the initial tests and fixes, I let it run for about one week. Since I capped the order value to 100 rs. and adjusted the params defensively, it didn't made huge profits.
In first half of the week, it made -23 rs. (yes negative)
And after a whole week, 47 rs. profit (total)
If I've increased the cap, it could've made more money (HOPE), but can't say it might screw up and I could've lost all money.
Because when I checked logs, I found some bugs again which is causing the buying/selling at unfavourable prices. After my semester exams, when I started debugging it again, that's when my ssd fails and since I killed my EC2 instance, the data was also gone. (All hard work gone)
π Things I Would Change (But I can't)
Now, that I think of what I could've improved if that project kept running?
- Putting in AI into my algo, so it could make more advanced decisions.
- Adding in some more information like market sentiments, trending crypto's, news sentiment regarding crypto and other factors so my algo can make more informed decisions.
- Use proper exception handling (not just try: except: print(e) π).
- Store logs in a database instead of a text file.
- Add a web dashboard for live alerts.
- Use design patterns like Strategy or Observer, because I now know they exist.
βοΈ Conclusion
This bot wasn't perfect, maybe my algo was the culprit or my lack of skills that created the bugs, or why haven't I pushed my code on github or... or... or..., but it taught me more about APIs, automation, and trading logic than most tutorials ever did. Sometimes, the best way to learn is to build something just a little beyond your understanding.
If youβre a dev who loves creating automation scripts and finds finance interesting β give it a shot. Build a bot. Lose some fake money. Learn a lot. π§
Thank you for reading about one of the coolest project I built and meet you again.
Umang Mittal
Singing off !!
Top comments (1)
its amazing. if you can build this reply me..
btw, check our product at auxodomain. cheap domain, vps and cloud server. Support ready 24/7..
Have a nice dayπππ