Skip to content

basimalii/Stock-Trading-Sim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A repository for CS3100 term project

Description

The Stock Trading Simulation Web App is a dynamic and interactive platform designed to simulate the real-world stock market trading environment. It’s a game where players can experience the thrill and strategy of stock trading without any actual financial risk.

From a player’s perspective, the game begins with registration and the allocation of a starting cash account. Players can then engage in buying and selling actions based on real-time NYSE prices, with the ultimate goal of maximizing the value of their portfolio by the end of the game. The game also offers optional features such as viewing competitors’ portfolios, tracking their own trading activities, and adapting to transaction fees. This provides an opportunity for players to learn about the stock market, develop trading strategies, and understand the impact of market trends on their portfolio.

From an admin’s perspective, they have the power to create and manage games. They set the starting time and amount for each game, maintain player login and profile information, and declare the winner based on the highest portfolio value at the end of the game. Admins also have the ability to customize game rules, providing flexibility in how the game is played.


Stock Trading Game Part-III

The UI implementation for the Stock Trading Game Part-III offers a seamless and intuitive experience for users to buy and sell stocks, manage portfolios, and compete in the game. Designed UI with HTML, CSS, and JavaScript, it provides a visually appealing and user-centric design that enhances the overall stock trading simulation experience.

  • Updated the description for Part-II as well to reflect some new changes made after implementing the UI on April 5, 2024.

Video Demo Link:

👉 Link to the Google Drive folder


Stock Trading Game Part-II

How to run the server and test the APIs?

Ensure that your MongoDB server is running and you are connected to MongoDB [brew services start mongodb-community & brew services stop mongodb-community for MacOS]. We are using localhost:3000 for this project. Navigate to the project folder in the terminal and install the required dependencies using npm install. Then, start the server by running node server/app.js or npm run dev. To run the unit tests, use npm run test or npx mocha tests/apiTest.js. All 10 tests are passing.

Make sure to make the requests in the following order initially, to ensure the database is correctly set up. I have provided example API calls for all the API endpoints at the end of Part-II description.

    // routes
    app.post('/updateAllStocks', writeAllStocksToCollection);
    app.post('/createUser', createUser)
    app.post('/createGame', createGame);
    app.get('/getCurrentGameSessions', getCurrentGameSessions);
    app.post('/addPlayerToGame', addPlayerToGame);
    app.post('/buyStock', buyStock);
    app.post('/sellStock', sellStock);
    app.get('/portfolio/:playerUsername', getPortfolio);
    app.get('/getTransactions/:playerUsername', getPlayerTransactions);
    app.post('/endGame', endGame);

Some Assumptions & Limitations

  • Due to the unavailability of free real-time data APIs, stock data is fetched from api.polygon.io for a specific date. It does not provide data for the current day before the closing time. Stock prices for buying and selling are based on the lowest and highest prices, respectively, for a stock symbol on the given date. Multiple API calls were avoided due to the lack of real-time updates for free plan members of polygon.io.

Layout of Files & Folders

  • server/app.js: Main server file with Express setup and route handling.
  • models/: Contains MongoDB schema and methods for database interaction.
  • routes/: Defines API endpoints and their corresponding handlers.
  • utils/: Holds utility functions for database operations and other common tasks.
  • tests/: Contains unit tests for API endpoints.

Architecture of JavaScript Code Files

  • Server Initialization: app.js sets up Express server and middleware.
  • Database Models: models/ files define MongoDB schema and methods.
  • API Routes: api.js defines endpoints and request handling.
  • Utility Functions: db.js in utils/ has functions for common tasks.
  • Testing: tests/ contains unit tests for API endpoints.

Features

This API provides functionality for the stock trading game. It allows users to register as players, buy and sell stocks, view their own and competitor's portfolios, and end the game to determine the winner. The 9 implemented features and their respective endpoints are as follows:

  • Register players for the game
    app.post('/addPlayerToGame', addPlayerToGame);
    
  • Provide all players with a starting cash account in their portfolio
    app.post('/createGame', createGame)
    
  • Allow player buy and sell actions at the current NYSE prices
    app.post('/buyStock', buyStock)` & `app.post('/sellStock', sellStock)
    
  • Keep track of each player's portfolio and its value
    app.get('/portfolio/:playerUsername', getPortfolio)
    
  • Declare a winner at the end of the game
    app.post('/endGame', endGame)
    
  • Maintain player login and profile information.
    Maintaining in the MongoDB collection called `userInfo`
    
  • Admin users that can create games
    app.post('/createUser', createUser)
    

Additional features:

  • Keeping track of all trades and activities of a player during the game
    app.get('/getTransactions/:playerUsername', getPlayerTransactions);
    
  • View competitor's portfolio
    app.get('/portfolio/:playerUsername', getPortfolio)
    

Tests

image

Endpoints

1. Update All Stocks

  • Description: Fetches all stock data from api.polygon.io and writes it to the database.
  • Method: POST
  • Endpoint: /updateAllStocks
  • Request Body:
    {
        "date": "2024-03-20"
    }
  • Response: 200 OK

2. Create User

  • Description: Creates a new user.
  • Method: POST
  • Endpoint: /createUser
  • Request Body:
    {
        "username": "testUser",
        "password": "testPassword",
        "isAdmin": false
    }
  • Response: 200 OK

3. Create Game

  • Description: Creates a new game.
  • Method: POST
  • Endpoint: /createGame
  • Request Body:
    {
        "startingCash": 1000
    }
  • Response: 200 OK

4. Get Current Game Sessions

  • Description: Retrieves information about current game sessions.
  • Method: GET
  • Endpoint: /getCurrentGameSessions
  • Response: 200 OK

5. Add Player To Game

  • Description: Adds a player to a game.
  • Method: POST
  • Endpoint: /addPlayerToGame
  • Request Body:
    {
        "playerUsername": "testUser",
        "gameId": "<gameId>"
    }
  • Response: 200 OK

6. Buy Stock

  • Description: Allows a player to buy stocks.
  • Method: POST
  • Endpoint: /buyStock
  • Request Body:
    {
        "username": "testUser",
        "stockSymbol": "AAPL",
        "quantity": 5
    }
  • Response: 200 OK

7. Sell Stock

  • Description: Allows a player to sell stocks.
  • Method: POST
  • Endpoint: /sellStock
  • Request Body:
    {
        "username": "testUser",
        "stockSymbol": "AAPL",
        "quantity": 2
    }
  • Response: 200 OK

8. Get Portfolio

  • Description: Retrieves a player's portfolio.
  • Method: GET
  • Endpoint: /portfolio/:playerUsername
  • Response: 200 OK

9. Get Transactions

  • Description: Retrieves a player's transaction history.
  • Method: GET
  • Endpoint: /getTransactions/:playerUsername
  • Response: 200 OK

10. End Game

  • Description: Ends the game and determines the winner.
  • Method: POST
  • Endpoint: /endGame
  • Request Body:
    {
        "gameId": "<gameId>"
    }
  • Response: 200 OK

Project Part-I

Screens

Homepage Homepage Trading Screen Trading

Features

ID Name Access By Short Description Expected Implementation Source of Idea
01 Player Registration Player Players register for a specific game Must implement Project instructions
02 Game Duration Admin Configure start/end of each game individually Likely to be done Lots of other games I know
03 Moving Average Player An added feature to candlestick charts Probably not unless it's easy Investopedia
04 Starting Cash Account Player Provides all players a starting cash account in their portfolio Must implement Project instructions
05 Buy and Sell Actions Player Allows players to buy and sell stocks at the current NYSE prices Must implement Project instructions
06 Portfolio Tracking Player Keeps track of each player’s portfolio and its value Must implement Project instructions
07 Winner Declaration Admin Declares a winner at the end of the game Must implement Project instructions
08 Player Login and Profile Information Admin Maintains player login and profile information Must implement Project instructions
09 Game Creation Admin Allows admin users to create games Must implement Project instructions
10 Competitor’s Portfolios Viewing Player Optional viewing of competitor’s portfolios Likely to be done Project instructions
11 Transaction Fees Player Optional costs to buy/sell transactions (fees) Likely to be done Project instructions
12 Trade and Activity Tracking Player Tracks all trades and activities of a player during the game Likely to be done Project instructions
13 Game Configuration Admin Time and starting amount game configuration Likely to be done Project instructions
14 Leaderboard Player Displays a ranking of players based on their portfolio values Must implement Inspired by Videogames
15 Market Trends Player Shows the overall trends in the stock market Likely to be done Inspired by pre-existing apps
16 Game History Player Allows players to view their past games and performances Likely to be done Inspired by Videogames
17 Game Invitations Player Allows players to invite others to join a game Probably not unless easy Inspired by Videogames
18 Game Notifications Player Sends notifications about game updates Likely to be done Inspired by Videogames
19 Admin Dashboard Admin Provides an overview of all games Must implement Project Instructions
20 Player Management Admin Allows admins to manage player accounts Must implement Inspired by Videogames
21 Game Rules Customization Admin Allows admins to customize game rules Likely to be done AI Chatbot
22 Stock Updates Player Provides real-time updates on stock prices Must implement AI Chatbot
23 Portfolio Analysis Player Provides analysis of a player’s portfolio Likely to be done AI Chatbot
24 Stock Recommendations Player Suggests stocks to buy or sell based on trends Probably not unless easy AI Chatbot
25 Game Duration Setting Admin Allows admins to set the duration of a game Must implement AI Chatbot
26 Player Communication Player Allows players to communicate with each other Probably not unless easy AI Chatbot
27 Stock Watchlist Player Allows players to create a watchlist of stocks Likely to be done AI Chatbot
28 Game Statistics Admin Provides statistics about each game Must implement AI Chatbot
29 Player Activity Log Admin Allows admins to view a log of player activities Must implement AI Chatbot
30 Stock History Player Shows the price history of a stock Likely to be done AI Chatbot

Implementation

Tools and packages

I plan on using the following tools and packages for this project:

  • Frontend: HTML, CSS, JavaScript, React
  • Backend: Node.js with Express.js and Mocha.js
  • Database: MongoDB (a NoSQL DBMS) for storing data.

App API

List of API calls expected to be supported by the server:

  1. GET /portfolio?player=playername&game=gameid:
    responds with the current portfolio of the player

  2. POST /sell?player=playername&game=gameid&stock=tickersymbol*&quant=nnn: requests that a pretend sale is made within the game responds indicating stock sale success or not and the price

  3. POST /buy?player=playername&game=gameid&stock=tickersymbol*&quant=nnn: Requests that a pretend purchase is made within the game, responds indicating stock purchase success or not and the price

  4. GET /leaderboard?game=gameid: Responds with the current leaderboard of the game

  5. GET /history?player=playername: Responds with the player’s game history

Stock API

For the Stock API, we could use the Alpha Vantage API. Here are some API calls we might use:

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •