KEMBAR78
DBMS Project | PDF | Databases | Web Application
0% found this document useful (0 votes)
149 views52 pages

DBMS Project

The document is a mini-project report on the development of a Real Time Stock Market Database Management application, created by students at SRM Institute of Science and Technology. The project aims to provide a web-based platform for users to monitor financial markets, manage portfolios, and receive price alerts using Python's PyWebIO framework and MySQL for data storage. It addresses the need for a user-friendly, customizable tool for both novice and experienced investors, allowing them to track investments and stay informed about market changes.

Uploaded by

s.shreeyaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views52 pages

DBMS Project

The document is a mini-project report on the development of a Real Time Stock Market Database Management application, created by students at SRM Institute of Science and Technology. The project aims to provide a web-based platform for users to monitor financial markets, manage portfolios, and receive price alerts using Python's PyWebIO framework and MySQL for data storage. It addresses the need for a user-friendly, customizable tool for both novice and experienced investors, allowing them to track investments and stay informed about market changes.

Uploaded by

s.shreeyaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

REAL TIME STOCK MARKET DATABASE

MANAGEMENT
21CSC205P - DATABASE MANAGEMENT SYSTEM

A MINI-PROJECT REPORT

Submitted By

S. SHREEYAAS [RA2311030020053]
MOULLESH VARMA P [RA2311030020055]
AREPALLI PRIYA RANJITH [RA2311030020058]
Under the guidance of
Dr. Visnu Dharshini. S , AP/CSE
(Assistant Professor, Department of Computer Science and Engineering)

of
BACHELOR OF TECHNOLOGY
in
COMPUTER SCIENCE AND ENGINEERING
of
FACULTY OF ENGINEERING AND TECHNOLOGY

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY RAMAPURAM,


CHENNAI-600089
APRIL 2025
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
(Deemed to be University U/S 3 of UGC Act, 1956)
BONAFIDE CERTIFICATE

Certified that this mini project report titled “Real Time stock market database
management” is the Bonafede work of “S.SHREEYAAS
[RA2311030020053] MOULLESH VARAMA P [RA2311030020055]
AREPALLI PRIYA RANJITH [RA2311030020058]” who has carried the project
work under my supervision. Certified further, that to the best of my knowledge, the
work reported herein does not form any other project report or dissertation on the
basis of which a degree of award was conferred on an occasion on this any other
candidate.

SIGNATURE
Dr. Visnu Dharsini .S ,AP/CSE
Assistant Professor,
Department of Computer Science and
Engineering,
SRM Institute of Science and Technology,
Chennai.
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY

RAMAPURAM, CHENNAI -600089

DECLARATION

We hereby declare that the entire work contained in this mini project report titled
“Real Time Stock Market Database Management “has been carried out by, S.
SHREEYAAS [RA2311030020053], MOULLESH VARAMA P
[RA2311030020055], AREPALLI PRIYA RANJITH [RA2311030020058] at
SRM Institute of Science and Technology, Ramapuram , Chennai – 600089.

Place: Chennai S. SHREEYAAS

Date: MOULLESH VARMA P

AREPALLI PRIYA RANJITH


ABSTRACT

This project develops a comprehensive web-based Market Tracker application using Python's
PyWebIO framework, designed to empower retail investors with robust tools for real-time
financial market monitoring, personalized portfolio management, and intelligent price alert
notifications. The system implements a secure authentication mechanism through username-
password verification, ensuring authorized access to sensitive financial data. At its core, the
application aggregates and displays dynamic market information for key financial instruments
including Nifty 50, Sensex, and Bitcoin, presenting this data with clear visual trend indicators
(upward, downward, or neutral movements) alongside precise timestamps to maintain temporal
context. The portfolio management module enables users to meticulously track their investments
by recording asset purchases with detailed parameters including quantity, buy price, and
transaction timestamps, while automatically computing real-time profit/loss metrics by comparing
these entries against current market valuations. Beyond passive tracking, the system incorporates
an advanced alert engine that allows users to configure custom price thresholds (both upper and
lower bounds) for their monitored assets, with immediate notifications triggered when these
predefined conditions are met. The technical architecture leverages MySQL for persistent data
storage, ensuring reliability and data integrity for critical user information including portfolio
holdings and alert configurations. The PyWebIO interface delivers an accessible yet powerful user
experience, combining responsive design elements with intuitive navigation to accommodate users
with varying technical expertise. Additional features include comprehensive portfolio analytics,
historical performance tracking, and a streamlined workflow for adding new assets or modifying
existing positions. This implementation demonstrates the effective integration of financial data
visualization, user-centric portfolio tools, and proactive market monitoring capabilities within a
single cohesive platform, showcasing Python's versatility in developing practical fintech solutions.
The modular code structure facilitates future enhancements such as multi-user support, expanded
asset classes, or integration with brokerage APIs, making it both a functional investment tool and
a foundation for more sophisticated financial applications.
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.


ABSTRACT
LIST OF FIGURES
LIST OF ABBREVIATIONS
1 INTRODUCTION 1
1.1 INTRODUCTION 1
1.2 PROBLEM STATEMENT 2
1.3 OBJECTIVE 3
1.4 SCOPE AND MOTIVATION 4
2 EXISTING SYSTEM 6

2.1 HARDWARE REQUIREMENTS 8


2.2 SOFTWARE REQUIREMENTS 10
3 DESIGN (ER DESIGN AND FRONT END 13
DESIGN)
3.1 ER DIAGRAM 13
3.2 ARCHITECTURE DIAGRAM 17
3.3 USE CASE DIAGRAM 21
3.4 SEQUENCE DIAGRAM 25
4 PROPOSED METHODOLOGY 28
4.1 MODULES DESCRIPTION 28
4.2 DATABASE CONNECTIVITY 29
5 IMPLEMENTATION 32
6 RESULT AND DISCUSSION 39
7 CONCLUSION 44
8 REFERENCE 45
LIST OF FIGURES

Table No Table Name Page No


3.1 ER-DIAGRAM 13
3.2 ARCHITECTURE DIAGRAM 17
3.3 USE CASE DIAGRAM 21
3.4 SEQUENCE DIAGRAM 25
6.1 LOG PAGE 39
6.2 LANDING PAGE 40
6.3 OPTION AVALIABLE 40
6.4 ASSESTS AVAILABLE 41
6.5 QUANTITY ENTRY 41
6.6 BUYING PRICE 42
6.7 ADDING ASSEST MESSAGE 42
6.8 ASSEST TABLE 43
6.9 PORTFOLIO TABLE 43

vi
LIST OF ABBREVIATIONS

API Application Programming Interface

CSS Cascading Style Sheets

DBMS Database Management System

ERD Entity-Relationship Diagram

ORM Object-Relational Mapping

PDF Portable Document Format

RDBMS Relational Database Management System

REST Representational State Transfer

SQL Structured Query Language

UI User Interface

UX User Experience

UUID Universally Unique Identifier

Supabase Open Source Firebase Alternative based on PostgreSQL

Flask A Python-based Web Framework

OSS Open Source Software

CSS3 Cascading Style Sheets Level 3

API Key Application Programming Interface Authentication Key

POST/GET HTTP Request Methods (used in form data communication)

1
CHAPTER 1

INTRODUCTION

1.1 INTRODUCTION

The Market Tracker is a dynamic and user-friendly web-based application built using
Python’s PyWebIO framework, with MySQL serving as the backend database. The primary
objective of this system is to enable users to monitor live market prices, manage a personal
investment portfolio, and receive price-based alerts for financial instruments. In the modern
financial landscape, where data changes every second and timely decisions are crucial, this
application aims to provide a simple yet effective platform that helps users stay informed
and make smarter investment choices. Upon launching the application, users are greeted with
a login screen where they must enter a valid user ID and password. This step ensures that
each user’s portfolio and alert preferences are stored and managed individually. Once logged
in, users can navigate through a set of well-defined options that allow them to view current
market data, add new assets to their portfolio, check the status of their existing investments,
create new alerts based on price thresholds, and monitor triggered alerts. The market data
displayed is currently hardcoded with placeholder values for major financial indices like
Nifty 50, Sensex, and Bitcoin to INR, each shown with its trend indicator (up, down, or
stable), real-time prices, and timestamps. These values can be integrated with live APIs for
real-world applications. Users can then add assets to their portfolio by specifying the
quantity and buy price. The system records this data into the MySQL portfolio table,
automatically timestamping each entry. To enhance user engagement, the application also
provides a feature for setting alerts. Users can choose to receive notifications when the price
of an asset goes above or below a user-defined threshold. These alerts are stored in the
alerts table and checked against current prices to see if any conditions are met. If an alert
is triggered, it is prominently displayed to the user, enabling timely action. Visually, the
application uses elements like markdown headers, styled tables, coloured text for profit/loss
indicators, and an introductory image to improve the user experience. Overall, the Market
Tracker combines simplicity with essential functionality, making it a valuable project for
students, beginners in finance tech, or anyone looking to develop a basic yet powerful market
monitoring tool with Python and SQL.

1
1.2 PROBLEM STATEMENT

In the modern era of finance and investment, access to real-time market data and
personalized portfolio management tools has become increasingly crucial for both beginner
and experienced investors. With the rapid fluctuations in stock indices, cryptocurrency
values, and other financial assets, there is a growing need for users to stay constantly
updated on market trends. Despite the availability of several advanced financial tools and
mobile applications, many of these platforms are either paid, overly complex, or lack
personalization features such as customizable alerts or simplified asset tracking tailored for
casual investors and students.

Beginners often find it difficult to navigate through these complex interfaces and are
overwhelmed by the abundance of features they may never use. Moreover, educational
institutions and student developers often struggle to find open-source solutions that are
simple to implement and flexible to modify for learning or project purposes. Additionally,
users may miss important opportunities for buying or selling assets due to the absence of a
timely notification system that alerts them when certain price conditions are met.

There is a clear gap in the availability of a lightweight, user-friendly, and interactive


platform that focuses specifically on helping individuals track selected market assets,
record their portfolio investments, and get notified when certain market conditions align
with their strategies. A system that offers these features in a clean, secure, and
customizable environment is the need of the hour.

To address this problem, we propose the development of a Market Tracker Web


Application using Python (PyWebIO) and MySQL. This application allows users to log in
securely, view live market data for selected assets like Nifty 50, Sensex, and Bitcoin to
INR, add their investments to a personal portfolio, and set up alerts based on price
conditions. The data is stored and retrieved using a MySQL database, ensuring persistence
and scalability.

The system not only provides a basic yet effective user interface to interact with real-time
data but also promotes financial awareness by giving users insights into their profit or loss
in a visual format. Custom alerts ensure users are always informed of market changes

2
relevant to them. This application is ideal for students, educational demonstrations, and
lightweight use cases where a full-fledged trading platform is not necessary.

By bridging the gap between simplicity and utility, this project empowers users to take
control of their investments through an accessible and functional platform

1.3 OBJECTIVE

The primary objective of the Market Tracker Web Application is to develop an intuitive,
user-centric platform that enables individuals to monitor market movements, manage
personal investment portfolios, and receive real-time alerts based on customizable price
thresholds. With a strong emphasis on accessibility, functionality, and simplicity, this project
aims to bridge the gap between complex financial platforms and the needs of everyday users,
especially students and beginner investors.

One of the core goals is to provide a streamlined interface where users can easily view real-
time data of major financial instruments such as Nifty 50, Sensex, and Bitcoin to INR. By
leveraging Python’s PyWebIO framework, the application ensures a web-based, interactive
experience without requiring users to set up front-end technologies like HTML, CSS, or
JavaScript. This not only simplifies development and deployment but also allows the
platform to be lightweight and responsive.

Another key objective is to implement a secure login system that enables users to create
accounts and log in to access their personal investment data. This ensures that each user's
portfolio remains private and secure. The use of a MySQL database enables structured
storage of login credentials, investment records, and alert preferences, offering efficient data
retrieval and update capabilities.

The platform also seeks to provide a portfolio management feature where users can add the
assets they’ve invested in, including details such as asset name, quantity, buying price, and
the current market price. The system calculates the user’s profit or loss and displays it
clearly, helping users better understand their financial positions.

An essential objective of the project is the alert system—users can set price-based conditions
for their tracked assets. When the live market price meets or exceeds the specified condition,

3
the system notifies the user. This functionality ensures users stay informed and can make
timely decisions without constantly monitoring the market manually.

Moreover, the project aspires to promote financial literacy and awareness among students
and novice investors by offering an educational and practical tool for learning how markets
operate. It supports experimentation and safe analysis of investment strategies in a risk-free
environment.

Ultimately, the Market Tracker project aims to deliver a functional, educational, and user-
friendly web-based application that can serve both as a learning tool and a basic personal
finance assistant, all built using Python and MySQL technologies.

1.4SCOPE OF THE PROJECT

The scope of the Market Tracker Web Application project extends to providing users with a
simplified and interactive platform to monitor financial assets, manage personal investment
portfolios, and receive alerts based on predefined market conditions. The system is primarily
designed for students, beginner investors, and individuals who want to stay updated on
financial market trends without using complex trading platforms. The project covers the
development of an integrated web interface using PyWebIO, backend processing with
Python, and database management through MySQL, ensuring seamless user experience and
data persistence.

This project supports real-time tracking of popular indices and cryptocurrencies, such as
Nifty 50, Sensex, and Bitcoin to INR. It is designed to fetch and display current prices
directly within the interface, thereby offering up-to-date market insights. The application
also allows users to register and log in to their personalized accounts. This ensures that each
user has a secure and individual environment to manage their investment records. The login
system provides an authentication mechanism that safeguards user data and prevents
unauthorized access.

4
One of the most important features within the scope of this project is portfolio management.
Users can add details such as the name of the asset, the quantity purchased, and the buying
price. The system then automatically computes the current value of each asset and calculates
profit or loss, giving users a clear overview of their financial standing. This scope also
includes allowing users to delete or update portfolio entries as required.

The alert system is another significant part of the project’s scope. Users can specify certain
price points at which they want to be notified. When the market price reaches the defined
threshold, the application triggers an alert, ensuring timely updates that help users act
promptly. This is especially useful for users who may not be able to continuously monitor
prices but want to respond to significant changes.

The scope also involves maintaining a user-friendly and responsive interface that requires
minimal technical knowledge to operate. While it does not include advanced features like
stock trading, complex analytics, or integration with brokerage APIs, it lays the foundation
for future enhancements in those areas. The scope focuses on core functionalities that offer
meaningful value without overwhelming the user.

In conclusion, the project’s scope covers the essential aspects of market tracking, user
account management, portfolio handling, and custom alerts, aiming to create a lightweight
yet powerful tool for anyone interested in financial awareness and basic investment
management.

5
CHAPTER 2

EXISTING SYSTEM

In the current financial technology landscape, there are multiple systems already in place
that serve the purpose of market tracking, portfolio management, and alert-based monitoring.
These systems are widely used by investors, traders, and analysts to stay informed about
real-time asset performance and make data-driven decisions. Popular platforms such as
Google Finance, Yahoo Finance, Zerodha Console, Groww, and Moneycontrol offer users
the ability to track stock prices, manage portfolios, and set alerts for market fluctuations.
However, each of these platforms has its own limitations and areas that restrict user-level
customization, especially for developers and students building specialized systems. Google
Finance, for example, provides real-time price tracking and simple watchlists, but it lacks a
robust alert mechanism that can send users notifications based on specific threshold values.
It does not allow for user-authored backend logic or SQL database integration, which makes
it less flexible for advanced analytics or tailored alert conditions. Yahoo Finance, while more
sophisticated, offers detailed charts, financial news, and some customization through
watchlists and alerts. However, its alert system is not user-defined based on logical
expressions, and it does not support custom backend code or integration with a developer’s
own database for storing personal data like asset purchase prices, quantities, or timestamped
records.

In India, platforms like Zerodha Kite and Console offer a brokerage-based view of the
market. Users can track their investments, view profit and loss reports, and set notifications
within the app’s limited environment. However, these features are heavily tied to actual
trading activities and often come with restrictions such as KYC verification, trading account
requirements, and lack of access to raw backend data. Groww and Upstox offer similar
services, providing a clean UI to buy/sell assets, manage mutual funds, and see portfolio
overviews. But again, such applications are mostly focused on end-user trading and not on
educational or analytical needs where students or researchers might want to simulate
transactions, calculate custom metrics, or analyze alerts triggered under specific conditions.
Another major limitation of these platforms is that they are mostly closed-source and do not
allow for SQL or API-level interaction unless you subscribe to enterprise-level APIs, which
are often costly and come with restricted usage quotas.

6
On the other hand, websites like TradingView do offer powerful charting tools and alert
mechanisms. Users can define alerts using technical indicators and mathematical logic.
However, TradingView is primarily tailored for chart-based traders and doesn’t store
personal purchase data like quantity and buy price unless integrated with a third-party
broker. It also lacks the capability to build a personalized portfolio database that stores
detailed transaction history, which is vital for academic and practical learning purposes.
Moreover, most alert notifications on such platforms are limited to either email or app
notifications, and the platform does not allow users to set up their own backend services to
track, modify, or enhance the alert mechanism further. Similarly, platforms like
Moneycontrol, while extremely informative and widely used, mainly focus on delivering
financial news, stock data, and analyst reports. It lacks real-time interactive features for user-
defined logic and doesn't provide a backend interface where users can store and manipulate
their own data sets.

From a technological standpoint, existing systems are generally built on top of proprietary
databases or cloud infrastructures that are inaccessible to the end user. This makes it
impossible for users to extend functionalities beyond what is already offered by the
company. For instance, if a user wishes to track their portfolio based on a self-calculated risk
metric or get alerts when their average buy price exceeds the market price by a certain
percentage, most existing systems do not allow such personalized configuration. Students,
developers, or data science enthusiasts aiming to work on financial datasets using Python,
Flask, or SQL backend technologies often face these limitations. They may want to learn
how to build alert logic, perform CRUD operations, analyze purchase behavior, or integrate
dashboards, but current systems do not allow for this level of control or transparency.

Another major drawback of current systems is the lack of educational or sandbox


environments where users can simulate market activity and test alert behavior without
making real trades. This makes them less suitable for project-based academic learning,
where students are expected to design, build, and test systems from the ground up. For
example, while platforms like Zerodha and Groww allow users to track assets, they do not
support mock portfolios or simulated environments where one can input hypothetical
buy/sell transactions and generate metrics based on those entries. Additionally, most
platforms do not support timestamped portfolio tracking where users can analyze how their

7
investment decisions changed over time, or how thresholds fluctuated historically—data
which is crucial for financial analysis and visualization.

In summary, while the existing systems are well-suited for general users and professional
traders, they do not offer the level of flexibility, customization, and educational value
required for student-led projects or developer-focused solutions. The absence of SQL-based
data storage, lack of backend logic integration, limited alert configuration, and inability to
simulate real-world scenarios are some of the primary gaps observed in current solutions.
These limitations form the basis for developing a custom Market Tracker System with
MySQL or SQLite as the backend, integrated with Python and Flask for a complete full-
stack experience. In the proposed system, users can manually input their portfolio data, track
asset performance in real-time or simulated time, and set alerts based on highly personalized
threshold logic—such as being notified when the current market price drops below the
average buy price or exceeds a user-defined target. This system would be fully customizable,
locally hosted or cloud-deployed, and suitable for both academic learning and personal use.
It also supports clean database design through SQL schema, ensures persistent data storage,
and enables alert logic to be configured, modified, or extended with ease using Python code.
Therefore, the proposed Market Tracker System fills in the key gaps left by existing systems
and offers an educational yet practical alternative tailored for learners, researchers, and
independent developers.

2.1 Hardware Requirements

The hardware requirements for running the Market Tracker Web Application are moderate,
as it is a web-based application developed using Python, PyWebIO, MySQL, and JavaScript.
The system operates smoothly on both development and client machines without the need
for high-end hardware. Below are the detailed hardware requirements:

2.1.1 Processor

• A modern processor such as Intel Core i3 or equivalent is the minimum requirement


for development and usage.

8
• A faster CPU, such as Intel Core i5 or higher, is recommended for improved
performance during development, especially when running local servers and
handling multiple processes.

2.1.2 Memory (RAM)

• A minimum of 4 GB of RAM is required for basic development tasks and running


the application.
• 8 GB or more RAM is recommended for smoother multitasking, running local
servers, and handling more complex operations during development and testing.

2.1.3 Storage

• At least 250 GB of free disk space is required for the operating system, software
installations, libraries, database files, and backups.
• An SSD (Solid State Drive) is recommended for faster performance in storing and
retrieving data. Additional space may be needed for storing temporary files, logs, and
any data backups.

2.1.4 Display

• A monitor with a minimum resolution of 1366×768 pixels is recommended for


development purposes.
• For better UI/UX testing and responsive design development, a higher resolution
display such as Full HD (1920x1080) is preferred.

2.1.5 Input Devices

• A keyboard and mouse are essential for development, navigation, and interaction
with the system during both development and usage.
• Touchscreen support is optional but can be useful for testing mobile responsiveness
if the application is accessed on mobile devices.

2.1.6 Network

• A stable internet connection is required for:

9
• Fetching real-time market data from external APIs (for example, financial
data for stocks, crypto, etc.).
• Accessing the MySQL database for user data and market information.
• Hosting or testing the application online through a local server or cloud-based
server.

2.1.7 Operating System

• The system is compatible with any operating system that supports Python and
modern web browsers, including:
• Windows 10 / 11
• macOS
• Linux distributions (e.g., Ubuntu, Fedora)

These specifications ensure smooth development, testing, and usage of the Market Tracker
Web Application across various devices and platforms, while supporting responsive design
and real-time features.

2.2 Software Requirements

The Market Tracker Web Application is developed using modern technologies. The
following software components are required for development, deployment, and user
interaction:

2.2.1 Operating System

• Compatible with Windows 10/11, Linux, and macOS.

• Supports cross-platform development through Python, JavaScript, and web


technologies.

2.2.2 Backend

• Python 3.8+ for backend development and handling business logic.

• Flask framework for creating server-side routes and API endpoints.

10
• MySQL for storing user data, market tracking data, and application configurations.

• pip for managing Python dependencies and packages.

• PyWebIO for building interactive web interfaces.

• Requests library for making API calls to external market data providers.

2.2.3 Frontend

• HTML5, CSS3, and JavaScript for structuring and styling the frontend.

• Bootstrap for responsive and mobile-friendly design.

• jQuery or Fetch API for handling dynamic content loading and asynchronous data
fetching from APIs.

• Chart.js or D3.js for data visualization, such as displaying stock prices and market
trends.

2.2.4 Database

• MySQL or SQLite (for local development) to store user information, market data,
and transaction history.

• The cloud-based MySQL database can be used for hosting the application in
production, allowing for seamless data storage and retrieval.

2.2.5 Development Tools

• VS Code or any preferred code editor for efficient coding and debugging.

• Git for version control and collaboration in managing the project codebase.

• Postman for testing APIs and endpoints for market data retrieval.

• Browser Developer Tools for frontend debugging and performance analysis.

2.2.6 Data Processing & Visualization

• Pandas for handling and processing financial data, including calculations and data
transformations.

• Matplotlib or Plotly for advanced data visualizations and charting, useful for
displaying market trends.

11
2.2.7 Browser Support

• Fully compatible with Chrome, Firefox, Edge, and Safari browsers.

• Ensures cross-browser compatibility and smooth user experience across various


platforms.

These software components together provide the necessary tools to develop, deploy, and
maintain the Market Tracker Web Application, offering a smooth user experience with real-
time market tracking and analysis.

12
CHAPTER 3

DESIGN (ER DESIGN AND FRONT-END DESIGN)

3.1 ER DIAGRAM:

Fig.3.1 ER diagram

The ER (Entity-Relationship) fig.3.1 illustrates a comprehensive model of a stock market


tracker system, designed to manage various types of users, their portfolios, trading activities,
stock information, corporate entities, and event-based promotions. At the heart of the system
is the "USER" entity, which acts as a parent class for three subtypes: ADMIN, BROKER,
and CUSTOMER. This type of specialization ensures that each user type has its own distinct
role within the system. The USER entity includes essential attributes such as UserID, Name,
Password, NIC (National Identity Card), Birthday, Address, and Phone. These details help
in user identification, communication, and security within the application.

13
ADMIN users are system-level users who manage overall operations and are identified with
an additional attribute called StaffNo. BROKER users, on the other hand, are trading
facilitators and possess a LicenseNo to confirm their legal trading capabilities. The
CUSTOMER subtype is the most interactive user category, directly involved with portfolio
management and stock transactions. Each customer is identified with a unique CustNo and
has attributes like Portfolio and CashAmount. The CUSTOMER entity also features a
recursive relationship named “refer,” where one customer can refer another. This feature
might be used for promotional or referral programs to encourage user expansion.

Each customer maintains a PORTFOLIO, allowing them to manage their investments in


various stocks. The PORTFOLIO is associated with STOCK through an ownership
relationship and LIMITED_ORDER through a containment relationship. The STOCK entity
plays a central role in this system. It contains multiple attributes such as Symbol, IndexNo,
Value, UpdateTime, Price, Lot, and Blocked. These properties define a stock’s identity and
its latest market status. Value and UpdateTime help track the price history of each stock,
while the Lot size indicates how many shares are traded together. The Blocked attribute may
represent stocks that are restricted from trading temporarily, perhaps due to regulatory issues
or company actions.

In addition to STOCK, a BACKUP_STOCK entity exists with similar attributes like


Symbol, UpdateTime, IndexNo, Value, Lot, and Price. This entity acts as a backup data
storage model to recover from system failures or to provide historical data for analysis. The
relationship between PORTFOLIO and STOCK allows customers to own multiple stocks,
and each stock can appear in several portfolios, forming a many-to-many relationship
mediated by LIMITED_ORDER.

The LIMITED_ORDER entity is crucial for capturing customer trading behavior. It allows
customers to place limit orders to buy or sell stocks at specific prices. It includes attributes
such as Type (Buy/Sell), Price, Quantity, TransactionTime, TransactionQuantity, and
TransactionPrice. This ensures that users can set conditions for trades that will only execute
when market conditions are met. The system also logs the actual transaction values when
trades are executed. These relationships and attributes together make the system capable of
tracking pending and completed orders.

14
Corporate activity is another important part of this system. The ACTIVITY entity represents
non-trading events such as seminars and promotions. It has attributes like ActivityID, Date,
Venue, Type, and Description. ACTIVITY has two subtypes: SEMINAR and
PROMOTION. These are organized by CORPORATION entities, which include attributes
like CorpRegNo, Name, Address, and Phone. This allows the system to keep track of which
corporations are hosting events and the details of each event. The PARTICIPATE
relationship links USER to ACTIVITY, capturing the many-to-many nature of such
interactions—multiple users can attend multiple events.

The CORPORATION entity also plays a significant role in issuing stocks. Each corporation
can issue multiple STOCKs, which is modeled using the "issue" relationship. This ensures
traceability of each stock back to the company that issued it, a necessary component in any
real-world financial system. The ownership and relationship flow from CORPORATION to
STOCK and from STOCK to PORTFOLIO reflects how shares are issued, bought, and held
in real life. The STOCK entity is central to various relationships in this diagram and provides
key insights into user engagement, market behavior, and corporate involvement.

From an architectural perspective, this system supports a wide range of functionalities, from
user management to transaction processing, data backup, corporate promotion, and real-time
market tracking. The ER model is designed with both flexibility and scalability in mind,
capable of handling complex user interactions, diverse data types, and layered relationships.
The use of generalization (for USER types and ACTIVITY types), aggregation (between
CUSTOMER and PORTFOLIO), and recursive relationships (within CUSTOMER)
demonstrates a thoughtful approach to ER design.

The system also supports referral-based user growth through the recursive “refer”
relationship among customers. This could be used in reward or loyalty programs to
incentivize customers to bring in new users. This feature is especially beneficial in marketing
and increasing user engagement. In terms of system functionality, ADMIN users might be
responsible for managing users, brokers, and system-wide settings. BROKERs could
manage customer portfolios or facilitate trades on behalf of customers, depending on system
rules. CUSTOMERS are the primary end-users, who can build their portfolios, track stock
prices, place orders, and attend events.

15
Furthermore, the inclusion of corporate activities such as seminars and promotions adds
another layer of engagement, allowing corporations to reach out to users for marketing,
education, or public relations purposes. This makes the system more than just a stock
tracker—it becomes a complete financial engagement platform. Corporations issuing stocks
and organizing promotional events help bridge the gap between investors and companies.
Meanwhile, users attending seminars and promotions provide learning and investment
opportunities, creating a healthy ecosystem.

In a real-world implementation, this ER model could be mapped to a relational database


using systems like MySQL or PostgreSQL. The USER table could be linked to specialized
tables for ADMIN, BROKER, and CUSTOMER using foreign keys. PORTFOLIO and
STOCK tables could be joined using a junction table with LIMITED_ORDER information.
The ACTIVITY table would be extended by separate SEMINAR and PROMOTION tables,
while CORPORATION tables would store event and stock issuance data.
BACKUP_STOCK could be scheduled for updates at regular intervals for recovery or
analytics.

Altogether, this ER diagram presents a strong foundation for building a robust market
tracking and trading application. It is capable of handling a wide array of financial operations
such as placing orders, tracking portfolios, managing user types, logging activity
participation, and linking stock information with issuing companies. The design ensures data
integrity, security, and flexibility. With appropriate indexing, triggers, and constraints in the
database, this ER model can support a high-performance financial application catering to
brokers, investors, and system administrators alike. It also allows seamless integration with
front-end platforms for mobile apps or websites, supporting secure login, real-time updates,
and portfolio analytics. Thus, the system effectively combines trading functionality, user
management, and corporate interaction into a single, coherent framework

16
3.2 ARCHITECTURE DIAGRAM:

Fig.3.2 architecture diagram

The architecture diagram(fig.3.2) of the Market Tracker Web App User Flow outlines a
detailed and systematic interaction between users, the web application, backend services like
MySQL and PyWebIO, and external Market Data APIs. This flow is designed to deliver a
seamless user experience for tracking market data, managing portfolios, and setting up price

17
alerts. At its core, this architecture ensures real-time interactions, secure access, dynamic
data fetching, and meaningful user feedback at every stage.

The process begins with the user initiating a session by accessing the login page. This
interaction flows from the User entity to the Web App interface. The web application
presents a login form where the user submits their credentials, typically a username and
password. This input is relayed to the backend, where it is verified against stored data in the
MySQL Database. A decision-making mechanism within PyWebIO validates the provided
credentials. If the credentials are accurate, the system returns a "Success" response,
triggering the Web App to display a welcome message and transition the user to the main
menu. If the credentials are incorrect, the system responds with a "Failure" outcome,
prompting the Web App to show an error message, ensuring the user is informed about the
invalid login attempt. This authentication step is fundamental to ensuring the system's
security and user privacy, preventing unauthorized access.

Once successfully logged in, the user enters the main functional zone of the application. The
user can select from various actions listed in the menu. One of the most critical
functionalities is viewing live market data. When the user selects this option, the Web App
sends a request to the Market Data API to fetch real-time data on stocks and assets. The API
returns the relevant data, which the Web App processes and displays in a user-friendly
format, often as a table with updated asset names, prices, and performance metrics. This
ensures the user remains up to date with the latest market trends, enabling informed
investment decisions.

Another vital feature of the app is portfolio management, which includes the ability to add
assets to a portfolio. When the user opts to add to the portfolio, a form is displayed allowing
input for asset symbol, quantity, and buy price. This data is submitted to the backend, where
the Web App interacts with the MySQL Database to insert a new record in the user’s
portfolio table. PyWebIO plays a role in confirming that the data insert operation is
successful. Once confirmed, the system displays a success message to the user, reinforcing
that the action was completed and that their portfolio now includes the newly added asset.

In addition to adding assets, users can also check their existing portfolio. When this option
is selected, the Web App sends a query to the database to retrieve portfolio details associated

18
with the current user. The MySQL Database returns a list of all assets owned by the user,
including quantity and buy price. To provide the most useful insights, the Web App then
queries the Market Data API to fetch the current prices for the listed assets. These prices are
then mapped with the stored portfolio data to show real-time values, profits or losses, and a
summary of the user's current financial position. This dynamic combination of static user
data and real-time market data enriches the decision-making process for the user.

The alert system is another powerful tool in this application. Users can add price alerts to
monitor specific stock prices. The process begins when a user selects the “Add Alert” option
from the menu. The app shows a form where the user can input details such as the stock
symbol, target price, and alert conditions (e.g., notify when the price drops below or rises
above a certain threshold). Upon submission, the Web App sends this information to the
backend, where PyWebIO confirms the insert action and records the alert details in the
database. A success message is shown, indicating that the alert is now active.

Once alerts are set, the user can also view and manage them through the "Check Alerts"
option. This triggers a query to the database to retrieve all alerts associated with the user.
The Web App then cross-references these alerts with current prices obtained from the Market
Data API. For each alert, the system compares the target price with the actual market price.
If a match is found (i.e., the condition for the alert is fulfilled), the system flags that an alert
has been triggered. This alert is then displayed prominently to the user, typically in a
notification-style interface. The app shows a list of all active alerts, whether triggered or
pending, keeping the user fully informed of any price changes they care about.

The real-time functionality of the alert mechanism is central to the value of this application.
It continuously checks the market for changes and acts instantly, enabling users to take
immediate action. This is particularly beneficial in volatile markets, where price swings can
significantly affect a portfolio’s performance. In terms of performance, this system
architecture supports modular and asynchronous operations. Web App handles user
interaction, UI rendering, and data requests. MySQL manages persistent data storage
including user credentials, portfolios, and alerts. PyWebIO serves as the backend logic layer
that handles database queries, data validation, and control flow. The Market Data API
functions as an external source of truth for real-time price information.

19
At the end of the session, the user may choose to log out. The Web App handles this by
ending the session and optionally clearing any cached session data. This ensures that no
sensitive information remains accessible and maintains user security. Overall, the design of
this architecture ensures that each component communicates effectively and independently.
The segregation of responsibilities ensures better scalability, maintainability, and security.
For example, even if the Market Data API experiences downtime, the core functions of
portfolio viewing and alert management can still proceed using cached or previously stored
data. Moreover, the layered interaction between frontend, backend, and external APIs creates
opportunities for easy extension in the future. Additional features like automated trading,
news feeds, or financial analytics could be added without disrupting the current system.

This Market Tracker Web App thus integrates core functionalities essential to investors and
casual users alike. By allowing seamless login, real-time data tracking, smart alerting, and
comprehensive portfolio management, the system stands out as a robust and user-centric
financial tool. Each step in the user flow has been carefully mapped to ensure not only logical
sequence but also performance and security. The diagram effectively illustrates how data
flows between various components, ensuring clarity and traceability of every interaction the
user initiates. This structured flow, combined with responsive backend processing and real-
time API integration, exemplifies a modern architecture fit for today’s dynamic financial
environments.

20
3.3 USE CASE DIAGRAM:

Fig.3.3 use case diagram

21
The Market Tracker Application (fig.3.3) is designed to assist users in monitoring financial
assets, setting custom alerts, and managing their investment portfolios. The application flow
begins when a user launches the application and is prompted to log in. This is the first critical
step to ensure security and personalized access. Upon login, the system checks the
credentials entered by the user. If the credentials are incorrect, the user is immediately shown
a login failure message along with an error prompt that allows them to retry. On the other
hand, if the credentials are valid, the user is directed to a welcome page, creating a smooth
and user-friendly transition into the application. This welcome page is often accompanied
by an introductory message or branding image that helps familiarize new users with the
platform’s functionality and purpose.

Once the welcome page has been displayed, the user is presented with the main action menu.
This action menu is the central navigation hub, allowing users to choose from several core
features: viewing live market data, adding assets to their portfolio, setting custom alerts,
checking active alerts, and reviewing the current status of their investment portfolio. Each
of these actions leads to a dedicated workflow that handles the selected process efficiently.

If the user chooses to view market data, the application fetches real-time financial data from
external APIs or databases. The data is then styled and formatted to be readable and
informative, typically displayed in a tabular format that includes asset names, current prices,
historical trends, and other vital statistics. This feature is essential for users who want to keep
up with the latest market movements or make informed decisions before making
investments.

The "Add to Portfolio" feature allows users to build a personalized list of assets they have
purchased or are monitoring. When the user selects this option, they are shown a form to
input relevant asset details, including the asset name, quantity, buy price, and any other
useful metrics. Once the user inputs the details, the system validates the input. If the input is
invalid—say due to incorrect formats or missing fields—the user is shown an error message.
If valid, the asset is successfully inserted into the database, and the user is notified with a
confirmation message. This feature is crucial for tracking individual investments and
calculating returns over time.

22
Similarly, the application provides functionality for setting price alerts through the "Add
Alert" path. This is particularly useful for active traders or users who wish to be notified
when certain price thresholds are reached. After choosing this path, the user is prompted to
fill in an alert form with details such as the asset name, target price, and notification
preference. As with portfolio additions, input validation occurs to ensure that the data entered
is accurate and complete. Invalid input leads to error messages, while valid entries are
inserted into the database and followed by a confirmation message. These alerts can help
users react quickly to market changes, minimizing risk and seizing opportunities.

The "Check Alerts" feature enables users to see whether any of their set alerts have been
triggered. This process begins by connecting to the database and checking if any alerts exist
for the user. If no alerts are found, the system shows a message indicating that no active
alerts are available. If alerts do exist, the system proceeds to fetch the latest market data
related to those alerts. It then compares current market values to the alert conditions. If any
alerts have been triggered—i.e., a stock price has crossed a predefined threshold—the system
displays these alerts in a table. Otherwise, it informs the user that no alerts have been
triggered. This automated alert-checking logic enhances the efficiency of the application by
constantly monitoring conditions and notifying the user without requiring manual tracking.

Another vital functionality is the ability to check the portfolio status. This feature fetches all
the assets previously added by the user and calculates their current value based on live
market data. If the user has not added any assets, the system displays a "Portfolio Empty"
message. Otherwise, it fetches the live prices of those assets and calculates the profit or loss
for each one by comparing current market prices with the original buy prices. The results are
styled and shown in a tabular format, which typically includes fields like current price,
original price, gain/loss amount, and percentage change. This real-time analysis allows users
to understand the performance of their investments at a glance.

The application architecture also includes important backend interactions. For each core
function—adding to portfolio, checking alerts, and viewing data—the system connects to a
MySQL database to store and retrieve user-specific information. Meanwhile, PyWebIO
handles the web interface logic, user input forms, and screen updates. Market data is fetched
from external APIs, ensuring the most recent and accurate prices are used for all
computations and comparisons. This modular architecture helps separate concerns—

23
database operations, business logic, and UI rendering—making the system more
maintainable and scalable.

All user actions eventually loop back to the central menu, allowing seamless navigation
between different features. The user can continue to use the application or choose to log out
at any time. Logging out ends the session securely, protecting sensitive user data.

In summary, the Market Tracker Application provides a full-fledged ecosystem for financial
asset management. The intuitive login system ensures secure access, while the action menu
centralizes key features. Viewing market data offers real-time updates. Portfolio
management allows users to track their investments, and the alert system helps users stay
informed of critical market changes. Portfolio status checks provide analytical insights to
guide future decisions. Each workflow is accompanied by robust validation and user
feedback mechanisms, making the experience smooth, interactive, and informative. This
flow not only enhances user engagement but also encourages smarter investment decisions
through data-driven insights.

24
3.4 SEQUENCE DIAGRAM :

The Market Tracker Web App is designed to streamline the process of monitoring market
data, managing user portfolios, and setting alerts based on user-defined conditions. It
involves five main components: the User, the Web App, the MySQL Database, the PyWebIO

25
interface, and the Market Data API. The interaction begins with the user entering their
username and password through the Web App. These credentials are then validated by
querying the user table within the MySQL database. If the credentials are correct, user data
is fetched and an authentication success message is sent back to the Web App, which then
shows a welcome message and the main menu. If the credentials are incorrect, an
authentication failure response triggers an error message on the interface. After successful
login, the user is presented with a main menu that provides access to various features
including viewing market data, adding assets to a portfolio, checking the portfolio status,
adding alerts, and checking existing alerts.

When the user opts to view market data, the Web App sends a request to the Market Data
API to fetch live asset prices and other relevant data. The raw market data is then received,
formatted, and styled using PyWebIO before being displayed to the user. This allows users
to get a real-time overview of current asset values and market trends. If the user chooses to
add assets to their portfolio, the Web App prompts them to input details such as the asset
name, quantity, and buy price. These inputs are validated, and if found valid, a request is
sent to the MySQL database to insert the new portfolio record. A success response results in
a confirmation message being shown, while any errors in insertion or input result in
appropriate error messages being displayed.

Another key feature allows users to check the current status of their portfolio. When selected,
the Web App queries the MySQL database’s portfolio table to retrieve the user's portfolio
data. Simultaneously, it fetches the current prices of these assets from the Market Data API.
The app then calculates profit or loss by comparing the buy price with the current price and
displays the results in a neatly formatted table using PyWebIO. This table includes the asset
name, quantity owned, original buy price, current market price, and the calculated gain or
loss, providing a quick summary of the user's investment performance.

Users can also set up alerts based on specific conditions. When the "Add Alert" option is
selected, the Web App prompts the user to input the asset name, a threshold price, and the
type of alert (for example, above or below a certain value). These alert inputs are validated
and, upon confirmation, a new alert record is inserted into the MySQL alerts table. On
successful insertion, a confirmation message is shown. If the inputs are invalid or if there’s
a database error, an appropriate error message is displayed to the user.

26
Lastly, users can check for active alerts they have set. The Web App sends a request to the
MySQL database to fetch the records from the alerts table. These alerts are then cross-
checked with live market prices fetched from the Market Data API. If any conditions match
(e.g., a stock price falls below or rises above the user-defined threshold), the system can
notify the user accordingly. This final feature ensures that users can stay on top of important
changes in asset prices without having to constantly monitor the market manually.

Throughout the entire workflow, the PyWebIO interface plays a crucial role in formatting
and styling the data for better visualization, while the MySQL database stores persistent user
data, portfolios, and alerts. The Market Data API is essential for providing real-time data,
ensuring that users always work with the most current information. Overall, the system is
modular and well-structured, offering a seamless and interactive experience for anyone
looking to monitor and manage market investments.

27
CHAPTER 4

Proposed Methodology (Modules Description and Database connectivity)

Database connectivity forms the backbone of the Market Tracker System, enabling seamless
integration between the Flask-based web application and the SQL database. This integration
facilitates secure, efficient storage and retrieval of crucial financial data such as user
portfolios and price alert configurations. By using MySQL (or any standard SQL-compatible
database), the system ensures consistent data management and integrity, supporting all
essential operations like user tracking, asset management, and dynamic alerting.

4.1 MODULE DESCRIPTION

SQL Database Setup

The system initializes the database schema with two core tables based on the project's Entity-
Relationship Diagram (ERD): portfolio and alerts.

sql
CopyEdit
-- Portfolio Table
CREATE TABLE IF NOT EXISTS portfolio (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
asset_name VARCHAR(255) NOT NULL,
quantity INT UNSIGNED NOT NULL,
buy_price DECIMAL(10, 2) NOT NULL,
buy_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Alerts Table
CREATE TABLE IF NOT EXISTS alerts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,

28
asset_name VARCHAR(255) NOT NULL,
threshold_price DECIMAL(10, 2) NOT NULL,
alert_type ENUM('above', 'below') NOT NULL
);

These tables serve specific purposes:

• portfolio: Stores all user holdings including the asset name, quantity, purchase price,
and timestamps.
• alerts: Captures user-defined price alerts and triggers based on threshold logic.

4.2 DATABASE CONNECTIVITY

Establishing Connection in Flask

The Flask backend uses Python’s mysql-connector-python or PyMySQL to connect to the


database server. The connection string typically includes host, user, password, and database
name.

bash
CopyEdit
pip install mysql-connector-python
python
CopyEdit
import mysql.connector

conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="market_tracker"
)

cursor = conn.cursor()

29
This connection object is reused throughout the Flask app for all read and write operations.

Executing Queries

Inserting a Portfolio Entry:

python
CopyEdit
@app.route('/add_asset', methods=['POST'])
def add_asset():
asset_name = request.form['asset']
quantity = int(request.form['quantity'])
buy_price = float(request.form['price'])
user_id = session['user_id']

cursor.execute("""
INSERT INTO portfolio (user_id, asset_name, quantity, buy_price)
VALUES (%s, %s, %s, %s)
""", (user_id, asset_name, quantity, buy_price))
conn.commit()
return redirect('/dashboard')

Setting Up a Price Alert:

python
CopyEdit
@app.route('/set_alert', methods=['POST'])
def set_alert():
asset_name = request.form['asset']
threshold_price = float(request.form['threshold'])
alert_type = request.form['type']
user_id = session['user_id']

cursor.execute("""
INSERT INTO alerts (user_id, asset_name, threshold_price, alert_type)
30
VALUES (%s, %s, %s, %s)
""", (user_id, asset_name, threshold_price, alert_type))
conn.commit()
return redirect('/alerts')

Schema Design & Optimization

The database schema is designed with normalization principles to avoid redundancy and
ensure scalability. Each table has a primary key, and user-related data is efficiently
referenced using user_id. Data types like DECIMAL are used for financial values to
maintain precision.

Security measures like parameterized queries prevent SQL injection. Indexing can be added
on columns like user_id, asset_name, and alert_type to improve query performance.

Real-Time Logic

For real-time tracking and alerts, the application can run background tasks using libraries
like APScheduler or Celery to periodically fetch live market data from APIs and compare
prices with user-defined thresholds, triggering email or in-app alerts when conditions are
met.

31
CHAPTER 5

IMPLEMENTATION

FRONTEND:
from pywebio.input import input, NUMBER, FLOAT, select
from pywebio.output import put_markdown, put_table, put_text, put_error,
put_image, put_row, put_column, style, span
from pywebio import start_server
import time
import mysql.connector
DATABASE_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': 'shreeyaas',
'database': 'market_data'
}

USER_DATA = {"RA2311030020053": "shreeyaas"}

def get_db_connection():
try:
mydb = mysql.connector.connect(**DATABASE_CONFIG)
return mydb
except mysql.connector.Error as err:
put_error(f"Error connecting to MySQL: {err}")
return None

def get_market_data():
# Replace with your actual data fetching logic
# For now, using more visually distinct placeholder data
return [
["Nifty 50", 22550.50, "⬆️", "2025-04-05 17:45:00"],

["Sensex", 74850.25, "⬇️", "2025-04-05 17:45:00"],

["Bitcoin to INR", 6550000.75, "➡️", "2025-04-05 17:45:00"]


]

def get_market_data_dict():
data = get_market_data()

32
return {item[0]: item[1] for item in data}

def view_market_data():
data = get_market_data()
put_markdown("## 📊 **Live Market Data**")
styled_data = []
for asset, price, trend, timestamp in data:
if trend == "⬆️":
styled_data.append([span(asset, style='color: green'),
span(f"{price:.2f}", style='color: green'), span(trend, style='color:
green'), timestamp])
elif trend == "⬇️":
styled_data.append([span(asset, style='color: red'),
span(f"{price:.2f}", style='color: red'), span(trend, style='color:
red'), timestamp])
else:
styled_data.append([asset, f"{price:.2f}", trend, timestamp])
put_table([["**Asset**", "**Price**", "**Trend**", "**Timestamp**"]]
+ styled_data)

def add_to_portfolio(user_id):
put_markdown("### ➕ Add Asset to Portfolio")
with put_row():
asset_name = select("Select Asset", ["Nifty 50", "Sensex",
"Bitcoin to INR"], span=4)
with put_row():
quantity = input("Enter Quantity", type=NUMBER, span=2)
buy_price = input("Enter Buy Price", type=FLOAT, span=2)

if asset_name and quantity is not None and buy_price is not None:


mydb = get_db_connection()
if mydb:
mycursor = mydb.cursor()
sql = "INSERT INTO portfolio (user_id, asset_name, quantity,
buy_price) VALUES (%s, %s, %s, %s)"
val = (user_id, asset_name, quantity, buy_price)
mycursor.execute(sql, val)
mydb.commit()
mycursor.close()

33
mydb.close()
put_text(f"✅ Added {quantity} units of {asset_name} to your
portfolio.")
else:
put_error("Please fill in all the details.")

def check_portfolio_status(user_id):
put_markdown("## 💼 **Your Portfolio Status**")
mydb = get_db_connection()
if mydb:
mycursor = mydb.cursor()
sql = "SELECT asset_name, quantity, buy_price, buy_timestamp FROM
portfolio WHERE user_id = %s"
mycursor.execute(sql, (user_id,))
portfolio_data = mycursor.fetchall()
mycursor.close()
mydb.close()

current_prices = get_market_data_dict()

portfolio_display = [["**Asset**", "**Quantity**", "**Buy


Price**", "**Current Price**", "**Profit/Loss**", "**Buy Timestamp**"]]
for item in portfolio_data:
asset, qty, buy_price, buy_ts = item
current_price = current_prices.get(asset, buy_price)
profit_loss = (current_price - buy_price) * qty
profit_loss_color = 'green' if profit_loss >= 0 else 'red'
portfolio_display.append([asset, qty, f"{buy_price:.2f}",
f"{current_price:.2f}", span(f"{profit_loss:.2f}", style=f'color:
{profit_loss_color}'), str(buy_ts)])

if portfolio_display:
put_table(portfolio_display)
else:
put_text("Your portfolio is currently empty.")

def add_alert(user_id):
put_markdown("### 🔔 Set Up New Alert")
with put_row():
asset_name = select("Select Asset for Alert", ["Nifty 50",

34
"Sensex", "Bitcoin to INR"], span=4)
with put_row():
alert_type = select("Alert me when price is", ["above", "below"],
span=2)
threshold_price = input(f"Enter threshold price to alert when
{alert_type}", type=FLOAT, span=2)

if asset_name and alert_type and threshold_price is not None:


mydb = get_db_connection()
if mydb:
mycursor = mydb.cursor()
sql = "INSERT INTO alerts (user_id, asset_name,
threshold_price, alert_type) VALUES (%s, %s, %s, %s)"
val = (user_id, asset_name, threshold_price, alert_type)
mycursor.execute(sql, val)
mydb.commit()
mycursor.close()
mydb.close()
put_text(f"✅ Alert added for {asset_name} when price is
{alert_type} {threshold_price}.")
else:
put_error("Please fill in all the alert details.")

def check_alerts(user_id):
put_markdown("## 🚨 **Your Active Alerts**")
mydb = get_db_connection()
if mydb:
mycursor = mydb.cursor()
sql = "SELECT asset_name, threshold_price, alert_type FROM alerts
WHERE user_id = %s"
mycursor.execute(sql, (user_id,))
alerts_data = mycursor.fetchall()
mycursor.close()
mydb.close()

current_prices = get_market_data_dict()
triggered_alerts = []
active_alerts_table = [["**Asset**", "**Threshold Price**",
"**Alert Type**"]]

35
if alerts_data:
for asset, threshold, alert_type in alerts_data:
active_alerts_table.append([asset, f"{threshold:.2f}",
alert_type])
current_price = current_prices.get(asset, None)
if current_price is not None:
if alert_type == 'above' and current_price >=
threshold:
triggered_alerts.append(f"🔔 Alert: {asset}
reached ₹{current_price:.2f} (Threshold: ₹{threshold:.2f} - Above)")
elif alert_type == 'below' and current_price <=
threshold:
triggered_alerts.append(f"🔔 Alert: {asset}
dropped to ₹{current_price:.2f} (Threshold: ₹{threshold:.2f} - Below)")
put_table(active_alerts_table)
else:
put_text("You have no active alerts set.")

if triggered_alerts:
put_markdown("### 🔥 **Recently Triggered Alerts**")
for alert in triggered_alerts:
put_text(alert)
else:
if alerts_data:
put_text("No alerts have been triggered recently.")

def main(user_id):
put_markdown(f"""
# 📈 **Market Tracker**
""")
put_markdown(f"### 👋 Welcome, **{user_id}**!")

# Attractive front page with image and intro


put_image(src="https://images.unsplash.com/photo-1579546929518-
9e396f3cc809?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=form
at&fit=crop&w=500&q=80", width="300px")
put_text("Track real-time market data, manage your portfolio, and set
up smart alerts.")

36
actions = [
"📊 View Market Data",

"➕ Add to Portfolio",

"💼 Check Portfolio Status",

"🔔 Add Alert",

"🚨 Check Alerts"


]

choice = select("Choose an action:", actions)

if choice == "📊 View Market Data":


view_market_data()
elif choice == "➕ Add to Portfolio":
add_to_portfolio(user_id)
elif choice == "💼 Check Portfolio Status":
check_portfolio_status(user_id)
elif choice == "🔔 Add Alert":
add_alert(user_id)
elif choice == "🚨 Check Alerts":
check_alerts(user_id)

def login():
put_markdown("# 🔑 **Market Tracker Login**")
username = input("Enter Username:", required=True)
password = input("Enter Password:", required=True, password=True)

if username in USER_DATA and USER_DATA[username] == password:


put_markdown(f"✅ Login successful. Welcome, **{username}**!")
main(username)
else:
put_error("Login failed. Incorrect username or password.")

if __name__ == "__main__":
start_server(login, port=8080, debug=True)

37
BACKEND :

CREATE TABLE IF NOT EXISTS alerts (

id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

user_id VARCHAR(255) NOT NULL,

asset_name VARCHAR(255) NOT NULL,

threshold_price DECIMAL(10, 2) NOT NULL,

alert_type ENUM('above', 'below') NOT NULL

);

CREATE TABLE IF NOT EXISTS portfolio (

id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

user_id VARCHAR(255) NOT NULL,

asset_name VARCHAR(255) NOT NULL,

quantity INT UNSIGNED NOT NULL,

buy_price DECIMAL(10, 2) NOT NULL,

buy_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

38
CHAPTER 6

RESULTS AND DISCUSSION

Fig.6.1LOGIN PAGE

39
Fig.6.2 LANDING PAGE

Fig.6.3 OPTION AVALIABE

40
Fig.6.4 ASSESTS AVAILABALE

Fig.6.5 QUANTITY ENTRY

41
Fig.6.6 Entering the buying price

Fig.6.7 Succefully adding the assest message

42
Fig.6.8 Describing the alert table

Fig.6.9 Describing the portfolio table

43
CHAPTER 7

CONCLUSION

In conclusion, the Market Tracker Web Application is a comprehensive and dynamic


platform designed to offer users real-time market insights and portfolio management
capabilities. By leveraging Flask as the backend framework and SQL as the database
management system, the application ensures smooth and secure handling of user data, stock
portfolio tracking, and market prices. The robust database connectivity, enabled by SQL
queries, allows the system to efficiently store, retrieve, and manipulate critical data, ensuring
a seamless user experience. The well-designed schema ensures data integrity and optimized
performance, which is crucial for a financial application where data consistency and real-
time updates are key. The application’s ability to integrate with live market data, allow user-
specific portfolios, and manage transaction histories makes it a valuable tool for users
looking to track their investments in the stock market. Through the use of modern
technologies such as Flask, SQL, and responsive front-end design, the Market Tracker
Web Application provides a user-friendly and scalable solution for financial tracking. The
project demonstrates the effective use of database-driven web applications, offering insights
into the practical implementation of database connectivity, CRUD operations, and handling
real-time data within the financial domain. Overall, this project not only serves as a
functional tool for users to manage their stock portfolios but also showcases the powerful
combination of Python, Flask, and SQL to create an efficient, secure, and maintainable web
application.

44
REFERENCE

• Supabase. (2025). Supabase Docs. Retrieved from https://supabase.com/docs


• Flask. (2025). Flask Documentation. Retrieved
from https://flask.palletsprojects.com
• OpenRouteService API. (2025). OpenRoute Documentation. Retrieved
from https://openrouteservice.org/dev/#/
• MDN Web Docs. (2025). HTML, CSS, and JavaScript Tutorials. Retrieved
from https://developer.mozilla.org
• Python Software Foundation. (2025). Python Official Docs. Retrieved
from https://docs.python.org
• W3Schools. (2025). Web Development Tutorials. Retrieved
from https://www.w3schools.com
• Bootstrap (if used for design). (2025). Bootstrap Documentation. Retrieved
from https://getbootstrap.com
• GitHub – supabase-community/supabase-py. (2025). Supabase Python Client
Library. Retrieved from https://github.com/supabase-community/supabase-py
• PostgreSQL Global Development Group. (2025). PostgreSQL Documentation.
Retrieved from https://www.postgresql.org/docs
• Font Awesome (if icons used). (2025). Icon Library. Retrieved
from https://fontawesome.com

45

You might also like