Ever missed out on selling a particular stock at the correct time? Probably because it is impossible to monitor stocks continuously throughout the day. Don't worry; this project is just for you. In my project, the stock I am monitoring is the cryptocurrency Bitcoin, and the currency used is USD. You can easily tweak the source code to monitor your desired stock and the currency you desire.
Video DemoHARDWAREThe Hardware components required for this project are:-
1. LED(You may use a buzzer in case you like sounds :) )
2. A 10k ohm resistor(this is required so that the LED does not get destroyed due to high current)
3. USB A to mini USB (for powering your bolt wifi module)
4. BOLT WiFi Module(this is where your hardware and software finally become one :) )
The softwares utilized are:-
1. Telegram(An instant chat messaging service mainly because it's free!!!)
2. Ubuntu OS(or any Linux distro of your choice)
3. Documentation | CryptoCompare Cryptocurrency Data API(from where we will be fetching our cryptocurrency stock price data)
HARDWARE CONNECTIONSLet's move onto the hardware connections first.
The LED which you are using has two legs. The longer leg is the positive terminal, while the shorter is negative. Wrap one end of the resistor along with the longer(positive) leg, similar to the picture below.
Now put the shorter leg of the LED in the GND port of the bolt WiFi module. Put the free end of the resistor in the 0 pin of the Bolt module. It should look like the below picture.
That's it; part 1 of the project is complete.
Note: Do not make the connections when your module is powered on, as it may destroy it.
SETTING UP TELEGRAMInstall Telegram on your mobile device(available in both play store and app store).
Swipe left on the home screen of the app and select new channel. Give name and description to your channel. (The channel name is global, and you would be able to create it only if it's available. You can keep any name of your choice; remember to note it down). In settings, ensure that the channel is public.
Now type botfather in the search button on telegram. Select the botfather, which has a blue tick next to it.
Type in the chatbox /start.
It gives you a list of commands with which you can do various things.
Type /newbot in the chatbox.
It will ask for details such as bot name and bot username.
After this, it will give you an HTTP API key. Save this key somewhere in your system as it will be required. After that, add the bot to your channel as an administrator(You'll have to search for the bot using the bot username). Make sure that the bot has permission to post messages.
In case you have any doubts follow this link Add Bot to your Telegram channel - FrontPage Help Center.
Code:bolt_api_key="Your bolt wifi module api key"
device_id="BOLTXXXXX"
telegram_chat_id="Channel id in telegram "
telegram_bot_id="Your telegram bot id"
FRAME_SIZE=5 #can be any value as per requirement
MUL_FACTOR=3 #can be any value as per requirementThis is the configuration file that we have created. The bolt API key and device id are present in your bolt cloud account. Click on the API tab after logging into your cloud account.
Click on the eye icon to view your API key. Then click on the clipboard icon beside it to copy it and save it. Your bolt device id is in the form of BOLTXXXXX, which you can view in your cloud account.
import requests #for making HTTP requests
import json #for handling json data
import time #for sleep operation
from boltiot import Bolt
import conf,math,statistics
def get_bitcoin_price():
URL="https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD"
response = requests.request("GET",URL,verify=False)
response = json.loads(response.text)
print("response is",response)
current_price = response["USD"]
return current_price
print(get_bitcoin_price())
trade_price=35000
mybolt=Bolt(conf.bolt_api_key,conf.device_id)
history_data=[]
def send_telegram_message(message):
"""Sends message via Telegram"""
url="https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage"
data={
"chat_id":conf.telegram_chat_id,
"text":message
}
try:
response= requests.request("POST",url,params=data)
print("This is the Telegram url")
print(url)
print("This is the telegram response")
print(response.text)
telegram_data=json.loads(response.text)
return telegram_data["ok"]
except Exception as e:
print("An error occurred while sending message")
print(e)
return False
def compute_bounds(history_data,frame_size,factor):
if len(history_data)<frame_size:
return None
if len(history_data)>frame_size:
del history_data[0:len(history_data)-frame_size]
Mn=statistics.mean(history_data)
Variance=0
for data in history_data :
Variance +=math.pow((data-Mn),2)
Zn=factor*math.sqrt(Variance/frame_size)
High_bound=history_data[frame_size-1]+Zn
Low_bound=history_data[frame_size-1]-Zn
return [High_bound,Low_bound]
while True:
sale_price=get_bitcoin_price()
try:
print("Current sale price is", sale_price)
print("Your selling price is", trade_price)
if sale_price>trade_price:
print("Turning on LED for 5 seconds")
response_1=mybolt.digitalWrite('0','HIGH')
print(response_1)
print("Sending message via telegram")
message="SALE PRICE IS HIGHER. TIME TO SELL SOME STOCKS"
telegram_status=send_telegram_message(message)
print("The telegram status is: ", telegram_status)
time.sleep(5)
response_1=mybolt.digitalWrite('0','LOW')
print(response_1)
time.sleep(5)
except Exception as e:
print("ERROR OCCURRED")
print(e)
bound=compute_bounds(history_data,conf.FRAME_SIZE,conf.MUL_FACTOR)
if not bound:
required_data_count=conf.FRAME_SIZE-len(history_data)
print("Not enough data for Z-score. Need ", required_data_count, "more data points")
history_data.append(sale_price)
print(history_data)
time.sleep(10)
continue
try:
if sale_price >bound[0]:
print("Stock is performing higher than expected. Sending message via telegram")
message="STOCK IS PERFORMING HIGHER THAN EXPECTED"
telegram_status=send_telegram_message(message)
print("The telegram status is: ", telegram_status)
elif sale_price<bound[1]:
print("Stock is performing lower than expected. Sending message via telegram")
message="STOCK IS PERFORMING LOWER THAN EXPECTED"
telegram_status=send_telegram_message(message)
print("The telegram status is: ", telegram_status)
history_data.append(sale_price);
except Exception as e:
print("ERROR: " ,e)
time.sleep(60)This is the code of the main program. As you can see in the fsym parameter, you can easily change it from BTC(Bitcoin) to say, ETH(ethereum). You can also select the currency of your choice, such as INR for Indian rupees, etc. For further reading, you can refer to this Documentation | CryptoCompare Cryptocurrency Data API.
The program also does a z score analysis to predict whether the price of the stock is fluctuating.
In short, the program detects whether the price of the stock is greater than your defined selling price. If it is, it blinks an led for 5 seconds and sends a message via your telegram bot. If the stock price is fluctuating, it detects an anomaly and sends a message via telegram informing you of the same as the below picture.
Thus, we have built your very own stock alert and analyzer machine. We can combine this with a buzzer as well in case we want to give a sound alert. The code can also be used for other market stocks using their respective APIs.






.png?auto=compress%2Cformat&w=48&h=48&fit=fill&bg=ffffff)





Comments