create account

How to Build a Simple Crypto Trading Simulator, Part 1 by febin

View this thread on: hive.blogpeakd.comecency.com
· @febin ·
How to Build a Simple Crypto Trading Simulator, Part 1
<html>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*6OmogGjAPetqUCiLIAHLCA.png" width="1440" height="765"/></p>
<p>I published this story earlier on <a href="https://hackernoon.com/how-to-build-a-simple-crypto-trading-simulator-part-1-4ccdddcd6b76">Hackernoon</a>.</p>
<p>I am not a trader, but the whole idea of trading crypto is so tempting. I don’t want to invest real money unless I know what I am doing. I wanted someplace to test my strategies.</p>
<p>So, I thought of building a Crypto Trading Simulator. The idea is to help beginner investor learn and experiment without losing real money. In this series, I will teach you how to build one. I have got a database which contains crypto prices of different exchanges between March 7th, 2018 and March 16th, 2018.In this story, we will build a simple crypto simulator in python which allows the user to invest in a cryptocurrency, then we will run a simulator to see how the performance of his crypto asset in the next 9 days<em><strong>.</strong></em>For now, we will display the best bid price for his asset, compare it with the initial investment and tell him if he made a profit or loss. <strong>In the coming stories, I will cover how to add live currency monitoring, how to write and test strategies, how to build the user interface, etc..</strong> Here’s a video of the simulator we are building today, you can also take a look at the project’s <a href="https://github.com/jamesfebin/CryptoTradingSimulator">Github Repository</a>. <strong>You need to download the database separately from</strong> <a href="https://drive.google.com/file/d/1OHhtrvOe-EWcX_8tipWo6tWYqkkYDkPw/view?usp=sharing"><strong>here</strong></a> <strong>and place it in the project’s directory.</strong></p>
<p>https://youtu.be/Hh-mvTV8E4Y</p>
<p><br></p>
<p>Pseudo Code</p>
<p>Before we jump into coding, we need to have clarity on what are the next steps. This is important, otherwise we will often have confusions. We use pseudo code to get clarity, a pseudo code is not real code, but a roadmap in our own language.</p>
<pre><code>Step 1: Welcome the user.&nbsp;</code></pre>
<pre><code>Step 2: We will fetch the cryptocurrency prices during March 7th, 2018 since our database starts at that time.&nbsp;</code></pre>
<pre><code>Step 3: We will ask the user to invest in one currency.</code></pre>
<pre><code>Step 4: Then, we will run the simulator to see how his crypto asset does in the next 9 days.&nbsp;</code></pre>
<pre><code>Step 5: We will find the best bid price for that currency, compare it with user's initial investment and display if he made a profit or loss.</code></pre>
<p>We don’t have to do the steps in that order, we can do whichever is easier first. Because having more things completed gives us confidence and we are likely to complete the whole project.The code used in this story uses Python 2.7&nbsp;.Let’s start by creating an empty folder, ex: “<em>CryptoSimulator</em>”. <em><strong>You also need to download the crypto price database from</strong></em> <a href="https://drive.google.com/file/d/1OHhtrvOe-EWcX_8tipWo6tWYqkkYDkPw/view?usp=sharing"><em><strong>here</strong></em></a> <em><strong>and place it inside your project folder.</strong></em><em>Make a file called “run.py”</em></p>
<p>Welcome</p>
<p>We will create a simple function called “<em>welcome</em>”. It does nothing great, just print a series of line, the program name, giving the user an idea of what the program is up to, in other words just saying “<em>Hi</em>”.</p>
<pre><code>def welcome():<br>
 &nbsp;&nbsp;print(“Simple Crypto Trading Simulator”)<br>
 &nbsp;&nbsp;print(“Hey Yo, you are back in time. It’s Wednesday, March 7, 2018 7:39 AM”)<br>
 &nbsp;&nbsp;print(“Here are the crypto currencies you can invest.”)<br>
 &nbsp;&nbsp;print(“Fetching prices … ”)</code></pre>
<p>Great, now we need to fetch the prices of the crypto currencies at March 7 2018&nbsp;, 7:39 AM.Since our database is based on sqlite3, we need to download the python library, you can do that using the following command.</p>
<pre><code>pip install sqlite3</code></pre>
<p>Now at the beginning of the file run.py&nbsp;, we need to import the library.</p>
<pre><code>import sqlite3</code></pre>
<p>Now let’s write the code to fetch prices from the beginning of the time and display it.In the database we have following columns, timestamp, first_leg, second_leg, ask, bid and the exchange name. If we consider the currency pair “<em>BTC/USD</em>”. The first leg would be BTC and the second leg is “<em>USD</em>”.In the following lines of code, we are fetching the prices at a given time.</p>
<pre><code>connection = sqlite3.connect(‘./currency_monitor.db’)<br>
cursor = connection.cursor()<br>
query = “SELECT first_leg, ask FROM prices WHERE &nbsp;&nbsp;&nbsp;&nbsp;timestamp=’1520408341.52' AND second_leg=’USD’;” &nbsp;&nbsp;&nbsp;cursor.execute(query)<br>
coinAskPrices = cursor.fetchall()<br>
 &nbsp;</code></pre>
<p>Now we will loop through the prices, remove duplicates, add then to python dictionary and print them.</p>
<pre><code>coins = {}<br>
for coinAskPrice in coinAskPrices:<br>
 &nbsp;&nbsp;&nbsp;if coinAskPrice[0] in coins:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;continue<br>
 &nbsp;&nbsp;&nbsp;coins[coinAskPrice[0]] = {“price”:coinAskPrice[1], “curreny”:coinAskPrice[0]}<br>
 &nbsp;&nbsp;&nbsp;print(“{} — ${} \n”.format(coinAskPrice[0], round(coinAskPrice[1],4)))<br>
 &nbsp;&nbsp;&nbsp;return coins</code></pre>
<p>If you don’t understand the code, don’t worry. Just download the repository, run it and tinker around and see what happens, slowly everything will start to sense.Now we will combine the above pieces of code into one single function “<em>fetchCoins</em>”.</p>
<p><img src="https://cdn-images-1.medium.com/max/1000/1*kxgyQkQ_qUlN4X-KXV_o5g.png" width="1000" height="274"/></p>
<p>Now that, the prices have been displayed, we will ask the user which crypto he wants to buy and how much. We will create a function called “<em>inputBuy</em>”.</p>
<pre><code>def inputBuy():<br>
 &nbsp;&nbsp;print(“Select the crypto curreny you want to buy? \n”)<br>
 &nbsp;&nbsp;curreny = raw_input(“”).upper()<br>
 &nbsp;&nbsp;print(“That’s great. How much quantity you want to buy? \n”)<br>
 &nbsp;&nbsp;quantity = float(raw_input(“”))<br>
 &nbsp;&nbsp;return curreny, quantity</code></pre>
<p>Now we need to find the price of the currency which the user is interested. We can simply do that by querying the python dictionary.</p>
<pre><code>price = coins[currency][‘price’]</code></pre>
<p>Then we need to pass these parameters to our simulator. Let’s put together these pieces of code into the main function.</p>
<p><img src="https://cdn-images-1.medium.com/max/800/1*Mod-hJpO_DVK8tZxbU3wAg.png" width="640" height="220"/></p>
<p>Yes, the “<em>runSimulation</em>” function is not defined yet, we will be doing that next. We can do this another file, create a file “simulator.py”</p>
<p>We need to import these libraries</p>
<pre><code>import sqlite3<br>
import datetime</code></pre>
<p>Now let’s define the function <em>runSimulation.</em></p>
<pre><code>def runSimulation(boughtPrice, quantity, currency):<br>
 &nbsp;valueThen = boughtPrice * quantity<br>
 &nbsp;bestPrice, timestamp = fetchBestBidPriceFromDB(currency)<br>
 &nbsp;bestValue = bestPrice * quantity<br>
 &nbsp;priceDifference = (bestValue — valueThen)/float(valueThen) * 100</code></pre>
<p>Here we are are calculating the total asset price at the time of buying, then we are finding the best price for that currency during March 7th and March 16th. Later we are calculating the difference to find, if the value increased or decreased.To find the best price, make a function called “<em>fetchBestBidPriceFromDB</em>”.</p>
<pre><code>def fetchBestBidPriceFromDB(currency):<br>
 &nbsp;&nbsp;connection = sqlite3.connect(‘./currency_monitor.db’)<br>
 &nbsp;&nbsp;cursor = connection.cursor()<br>
 &nbsp;&nbsp;query = “SELECT max(bid),timestamp from prices WHERE first_leg=’{}’ and second_leg=’USD’ and timestamp&gt; ‘1520408341.52’”.format(currency)<br>
 &nbsp;&nbsp;cursor.execute(query)<br>
 &nbsp;&nbsp;rows = cursor.fetchone()<br>
 &nbsp;&nbsp;return rows[0], rows[1]</code></pre>
<p>We also need to add few more lines in the runSimulation function to print our findings.</p>
<pre><code>print(“The best bid price for {} was ${} at {} \n”.format(currency, bestPrice, time))<br>
if priceDifference&gt;0:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;print(“Your total asset value is ${}, it has increase by {}% \n”.format(round(bestValue, 4), round(priceDifference,2)))<br>
else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;print(“Your total asset value is ${}, it has decreased by {} \n”.format(round(bestValue, 4), round(priceDifference,2)))</code></pre>
<p>Let’s put these pieces of code together.</p>
<p>It’s almost done, but I want to add some drama. You know in the movies, the letters get printed one by one in the console?Create a file called “<em>drama.py</em>” and add these lines of code</p>
<pre><code>import time<br>
import sys</code></pre>
<pre><code>def dramaticTyping(string):<br>
 &nbsp;&nbsp;for char in string:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;sys.stdout.write(char)<br>
 &nbsp;&nbsp;&nbsp;&nbsp;sys.stdout.flush()<br>
 &nbsp;&nbsp;&nbsp;&nbsp;time.sleep(0.10)</code></pre>
<p>Now import this file on <em>run.py</em> and <em>simulator.py</em>, then replace the function call <em>print</em> with <em>dramaticTyping</em>.</p>
<p>Congrats, we have got a basic version of our crypto trading simulator ready.</p>
<p><br></p>
<p><br></p>
</html>
properties (22)
authorfebin
permlinkhow-to-build-a-simple-crypto-trading-simulator-part-1
categorycryptocurrency
json_metadata{"tags":["cryptocurrency","bitcoin","programming","coding","technology"],"image":["https://cdn-images-1.medium.com/max/2000/1*6OmogGjAPetqUCiLIAHLCA.png","https://img.youtube.com/vi/Hh-mvTV8E4Y/0.jpg","https://cdn-images-1.medium.com/max/1000/1*kxgyQkQ_qUlN4X-KXV_o5g.png","https://cdn-images-1.medium.com/max/800/1*Mod-hJpO_DVK8tZxbU3wAg.png"],"links":["https://hackernoon.com/how-to-build-a-simple-crypto-trading-simulator-part-1-4ccdddcd6b76","https://github.com/jamesfebin/CryptoTradingSimulator","https://drive.google.com/file/d/1OHhtrvOe-EWcX_8tipWo6tWYqkkYDkPw/view?usp=sharing","https://youtu.be/Hh-mvTV8E4Y"],"app":"steemit/0.1","format":"html"}
created2018-04-06 05:01:30
last_update2018-04-06 05:01:30
depth0
children1
last_payout2018-04-13 05:01:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,535
author_reputation245,954,781
root_title"How to Build a Simple Crypto Trading Simulator, Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id48,602,389
net_rshares0
@steemitboard ·
Congratulations @febin! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/firstpost.png)](http://steemitboard.com/@febin) You published your First Post
[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/firstvoted.png)](http://steemitboard.com/@febin) You got a First Vote

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click [here](https://steemit.com/@steemitboard)

If you no longer want to receive notifications, reply to this comment with the word `STOP`

> Upvote this notification to help all Steemit users. Learn why [here](https://steemit.com/steemitboard/@steemitboard/http-i-cubeupload-com-7ciqeo-png)!

Do not miss the [last announcement](https://steemit.com/easter/@steemitboard/celebrate-easter-with-steemitboard-the-eggs-opened-and-guess-what-popped-out) from @steemitboard!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-febin-20180406t084602000z
categorycryptocurrency
json_metadata{"image":["https://steemitboard.com/img/notifications.png"]}
created2018-04-06 08:46:00
last_update2018-04-06 08:46:00
depth1
children0
last_payout2018-04-13 08:46:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length992
author_reputation38,975,615,169,260
root_title"How to Build a Simple Crypto Trading Simulator, Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id48,627,119
net_rshares0