Stonks: Trading Simulator And A Positive Community For Learning Stock Market Trading

Stonks: Trading Simulator And A Positive Community For Learning Stock Market Trading

The Stonks app is the perfect way to learn about Stocks trading without any risk. With the Stonks virtual trading simulator, you can trade and invest in stocks without spending any real money. Plus, detailed candlestick charts and a USD converter will help track prices and trends. And if you want to compete with others, a global leaderboard will let you see how you stack up. Stonks also have a positive community where user can share their experiences, learning and advices. Stonks also has an AI chatbot BILLY, which can help users to learn more about stocks and learn about their history before investing.

Link to the GitHub Repository

Link to hosted Web App.

Android App - https://drive.google.com/file/d/1xKaU2pzFvt9LDsh5msl9Eup05f7jQlTL/view?usp=sharing

Demo Video

Web App

Android App

Motivation To Create Stonks

I have always wanted to learn stock trading, but being a college student with limited funds has made it difficult to pursue. That's why I decided to create Stonks, a real-time trading simulator, which allows users to practice trading without risking any real money. Stonks aims to provide a platform for users to learn about the stock market and investing in a safe and controlled environment.

Stonks also features a positive community with robust SPAM and abuse detection with the help of MindsDb where users can interact with each other, ask questions, and learn more about trading from experienced members.

Trading can be intimidating for beginners, which is why I have implemented an AI assistant named Billy with the help of MindsDb and OpenAI, which can help users learn more about each stock and answer any questions they may have. This AI assistant will save the user time searching for answers to their questions while also allowing them to learn more about the company in which they want to invest.

Features

Login Page

Stonks provides email authentication as well as Google sign-in features for ease of using the app.

Dashboard

Dashboard page

Search Stocks

Search page

Stock Details page - Candlestick chart:

Candlestick chart

Stock Details page - Line chart:

Line Chart

Buy Stocks

Buy Stock

Sell Stocks

Sell Stock

Live Chat & Billy Chatbot At Each Stock Page

Portfolio

Portfolio

Watchlist

Watchlist

Global Leaderboard

Stonks Community

Tech Stack

  • React Js

  • Tailwind

  • Firebase - For Authentication(Native/web), Push Notification

  • Node Js & Express - For creating backend APIs

  • Typescript - Backend is written in Typescript

  • MindsDB - For integrating AI/ML capabilities with the help of SQL

  • Capacitor JS - For Creating a Native App

  • Hosted the Frontend on Netlify & Backend on Linode

Challenges

Creating A Social Media/Forums Is Scary

There are numerous tutorials available on the internet about how to create a social media platform. However, running clones of those platforms in a production environment can be daunting. As the user base increases, maintaining a peaceful and positive community becomes more challenging due to the rise in hate speech and spam. These issues can negatively impact the growth of the app and reduce its value and credibility.

To address these concerns and create a community feature for Stonks, I integrated an advanced ML model for detecting abuse and spam with the help of SQL. I accomplished this with the help of MindsDb, which has seamless integration with HuggingFace and OpenAI.

MindsDB helps to combine database capabilities with popular AI frameworks. Let's take a look at how I used MindsDB to secure my community.

CREATE MODEL abuse_detection
PREDICT sentiment
USING engine='huggingface',
  model_name= 'unitary/toxic-bert',
  input_column = 'comment',
  labels=['toxic','obscene','insult','severe_toxic','identity_hate','threat'];

The SQL statement above creates a machine-learning model in MindsDB. The purpose of the model is to predict the sentiment of a given comment, including whether it contains language that is toxic, obscene, insulting, severely toxic, related to identity hate, or threatening. The model is constructed using Hugging Face, which is a widely-used deep learning library. Specifically, it uses a pre-trained model called "toxic-bert". The dataset being analyzed will have a column named "comment", which will store the text of the comments. The model is trained to recognize the six possible labels mentioned above, enabling it to classify new comments appropriately.

Using a MindsDB model is very easy. To get started, simply install the official MindsDB JavaScript SDK. I am using express with typescript.

npm i mindsdb-js-sdk
import MindsDB from "mindsdb-js-sdk";

export async function connectMindsDB() {
  try {
    const user: string = process.env.MINDSDB_USER as string;
    const password: string = process.env.MINDSDB_PASSWORD as string;

    const res = await MindsDB.connect({
      user,
      password
    });

  } catch (error) {
    // Failed to authenticate.
    console.log(error);
  }
}

The above code imports the MindsDB JavaScript SDK and exports an asynchronous function called connectMindsDB.

Inside the connectMindsDB function, it first attempts to retrieve the MINDSDB_USER and MINDSDB_PASSWORD environment variables using the process.env object. The as string assertion tells TypeScript that these variables should be interpreted as strings.

Next, the function attempts to connect to MindsDB using the MindsDB.connect() method, which takes an object containing user and password properties. This method returns a Promise, which is resolved with a response object if the connection is successful.

If there is an error, the catch block will log the error to the console.

Now in app.ts just import the file and run connectMindsDB() function.

// check toxicity of comment
  const fetchCommnentToxicity = await MindsDB.SQL.runQuery(
    `SELECT * FROM abuse_detection1 WHERE comment='${body}';`
  );

Checking for toxicity is easy with the MindsDB library. You can now write an SQL query to access and run your machine learning model. How cool is that?! 🤯🤯


// @desc  ADD A NEW COMMENTS
// @route GET /api/comment
// @access PRIVATE
export const addComment = expressAsyncHandler(async (req: Request, res: Response) => {
  const { body, postId, userId }: { body: string; postId: string; userId: string } = req.body;

  // check toxicity of comment
  const fetchCommnentToxicity = await MindsDB.SQL.runQuery(
    `SELECT * FROM abuse_detection1 WHERE comment='${body}';`
  );

  const commentToxicity = fetchCommnentToxicity?.rows[0]?.sentiment_explain;

  const isToxic = isToxicFunc(commentToxicity);

  if (isToxic) {
    throw new Error(
      "Your comment potentially violates our community rules; please help us maintain a healthy environment for the community. Please check your language of the comment."
    );
  }

  const post = await db.comment.create({
    data: {
      body,
      postId,
      userId
    }
  });

  res.json(post);
});

The above is an API that throws an error with a message asking the user to abide by community guidelines if they write a toxic comment.

Pardon my language, just for demo purposes

For spam detection, I used gpt3 powers to classify comments on the post as spam or not spam.

CREATE MODEL spam_detection_gpt3
PREDICT sentiment
USING
  engine = 'openai',
  prompt_template = 'Act like a advance spam filter classify comment
  strictly as "spam", "not-spam".
  "{{comment}}.":';

Now, we can query to check if the comment on the post is spam.

SELECT comment, sentiment
FROM spam_detection_gpt3
WHERE comment = 'crypto buy crypto, click link in the here';

Here's the result.

Error message if the user writes a spam comment

Creating a Cross Platform App

To create a better user experience for Stonks, I decided to build an Android app. While the web app is accessible from any device with an internet connection, a native app can offer more seamless integration with the device's hardware and software.

To build the Android app, I used Capacitor JS by Ionic. Capacitor is a cross-platform framework that allows developers to build web apps that can be deployed as native apps on Android and iOS. By using Capacitor, I was able to leverage my existing web development skills and build an app that could be used by Android users.

In addition to the core features of the Stonks app, I also included two key native features in the Android app: Google authentication and push notifications. Google authentication allows users to sign in to the app using their existing Google account, which can save them time and improve the security of their login. Push notifications allow the app to send notifications to the user's device, even when the app is not open, which can help keep users engaged with the app and up-to-date on their investments.

Overall, by creating an Android app with Capacitor and including native features like Google authentication and push notifications, I believe I have significantly improved the user experience for Stonks users on Android devices.

PS: I don't have a MacBook or iPhone, so I haven't been able to test the Stonks native iOS app myself. At present, the native app is only available for Android devices, for iphone you can test the web app.

Creating Billy - AI Assistant ChatBot For Stonks

Trading can be a complex and intimidating field for beginners, as there are many factors to consider when deciding which stocks to buy or sell. To help with this, I have created an AI assistant Billy, which can use natural language processing (NLP) to help users learn more about each stock and answer any questions they may have.

MindsDb and OpenAI are both AI technologies that can be used to build these types of AI assistants. MindsDb is an open-source, automated machine learning platform that makes it easier to build and deploy predictive models, while OpenAI is a leading research organization that focuses on developing advanced AI systems.

Using these technologies, I was able to create Billy in just an hour. I was able to develop an AI assistant that can provide users with information about different stocks quickly and easily, such as their financial performance, industry trends, and potential risks or opportunities. This can save users a lot of time and effort that they might otherwise spend researching each stock on their own.

In addition, Billy can also help users learn more about the companies they are interested in investing in, which can help them make more informed decisions about their investments. This can be particularly useful for beginners who are still learning about the stock market and how to invest wisely.

CREATE MODEL financial_bot_gpt3
PREDICT answer
USING
    engine = 'openai',
    prompt_template = 'answer the question of text:{{question}} about text:{{article_title}}';
    question = 'question',
    context = 'context',

The above SQL query creates an AI model using openai gpt.

// @desc GET BILLY CHATBOT
// @access PRIVATE
export const billyChatBot = asyncHandler(async (req: Request, res: Response) => {
  const { context, question }: { context: string; question: string } =
    req.body;


  console.log("context", context, question)
  const answer = await MindsDB.SQL.runQuery(`
    SELECT context, question, answer FROM financial_bot_gpt3 WHERE context = '${context}' AND question = '${question}';
  `)

  res.json(answer?.rows[0]);
});

The above API is a Node.js endpoint for a private access route that serves a chatbot service called "billyChatBot".

The endpoint is expecting a POST request with a JSON payload that includes two properties: "context" and "question", both of type string. These properties are extracted from the request body using the destructuring syntax.

Once the context and question are extracted from the request, the API uses the MindsDB SQL library to run a query against a database table called "financial_bot_gpt3". The query selects the "context", "question", and "answer" columns from the table where the context and question match the values sent in the request payload.

The query result is then returned as a JSON object in the response to the client. If there is a match, the response includes the answer to the question from the chatbot. If there is no match, the response will be an empty object.

References

Did you find this article valuable?

Support WebDrip Narottam by becoming a sponsor. Any amount is appreciated!