Crypto Demo Portfolio in Python (FastAPI, React, EchoAPI)

NeuralNineAbout 7 min readMay 31, 2025Watch original
THE SUMMARYAI-generated

Key Concepts

  • FastAPI: A modern, high-performance web framework for building APIs with Python.
  • SQLAlchemy: A Python SQL toolkit and Object-Relational Mapper (ORM) that gives application developers the full power and flexibility of SQL.
  • Pydantic: A Python library for data validation and settings management using type annotations.
  • JWT (JSON Web Token): A standard for securely transmitting information between parties as a JSON object. Used here for authentication.
  • React: A JavaScript library for building user interfaces.
  • TypeScript: A superset of JavaScript that adds static typing.
  • Echo API: A tool for testing APIs, offering features like AI-powered test generation and documentation.
  • Cursor: An AI-powered code editor used to accelerate front-end development.
  • Binance API: A cryptocurrency exchange API used to fetch real-time market data.
  • Oauth2: An authorization framework that enables applications to obtain limited access to user accounts on an HTTP service.

Backend Implementation (FastAPI)

1. Project Setup

  • A new directory called "backend" is created for the FastAPI project.
  • The following Python packages are installed using pip: fastapi, sqlalchemy, jwt, requests, and pydantic.

2. Models (models.py)

  • Defines the database schema using SQLAlchemy.
  • Imports necessary modules from SQLAlchemy: Column, Integer, String, Float, ForeignKey, DateTime, relationship, and declarative_base.
  • Creates a base class for declarative models using declarative_base.
  • Defines the following database tables as Python classes:
    • User:
      • id: Integer, primary key, indexed.
      • username: String, indexed, unique.
      • password: String.
      • portfolio: Relationship to the Portfolio class.
    • Portfolio:
      • id: Integer, primary key, indexed.
      • user_id: Integer, foreign key referencing User.id.
      • total_added_money: Float, default 0.0.
      • available_money: Float, default 0.0.
      • user: Relationship to the User class.
      • assets: Relationship to the Asset class.
      • transactions: Relationship to the Transaction class.
    • Asset:
      • id: Integer, primary key, indexed.
      • portfolio_id: Integer, foreign key referencing Portfolio.id.
      • symbol: String (e.g., "BTC").
      • quantity: Float.
      • portfolio: Relationship to the Portfolio class.
    • Transaction:
      • id: Integer, primary key, indexed.
      • portfolio_id: Integer, foreign key referencing Portfolio.id.
      • symbol: String.
      • quantity: Float.
      • price: Float (price at the time of the transaction).
      • timestamp: DateTime.
      • portfolio: Relationship to the Portfolio class.

3. Schemas (schemas.py)

  • Defines Pydantic models for request body validation.
  • UserCreate:
    • username: String.
    • password: String.
  • AddMoney:
    • amount: Float.
  • TradeAsset:
    • symbol: String.
    • quantity: Float.

4. Main Application (main.py)

  • Imports necessary modules, including FastAPI, SQLAlchemy, JWT, requests, and the models and schemas defined earlier.
  • Creates a FastAPI app instance: app = FastAPI().
  • Configures OAuth2 password bearer scheme for authentication: oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token").
  • Adds CORS middleware to allow cross-origin requests from the front end. The configuration is overly permissive (allow_origins=["*"]) for simplicity, which is not recommended for production.
  • Sets up the database connection using SQLite:
    • Creates an engine using create_engine("sqlite:///./cryptoc_folio.db", connect_args={"check_same_thread": False}).
    • Creates a session maker using sessionmaker(autocommit=False, autoflush=False, bind=engine).
    • Creates the database tables using Base.metadata.create_all(bind=engine).
  • Defines a secret key for JWT encoding and decoding.
  • Helper Functions:
    • get_db(): A dependency injection function that provides a database session to the API endpoints. It uses a try...finally block to ensure the session is closed after use.
    • get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): Authenticates the user based on the JWT token. Decodes the token using the secret key, retrieves the user from the database, and returns the user object. Raises an HTTPException with status code 401 (unauthorized) if the token is invalid or the user is not found.
    • get_crypto_price(symbol: str): Fetches the current price of a cryptocurrency from the Binance API. Returns 0.0 if the API call fails.
  • API Endpoints:
    • POST /register: Registers a new user. Creates a new user and an associated portfolio in the database. Returns a success message.
    • POST /login: Logs in an existing user. Validates the username and password, generates a JWT token, and returns the token.
    • POST /add_money: Adds money to the user's portfolio. Requires authentication.
    • POST /buy: Buys a cryptocurrency asset. Requires authentication.
      • Retrieves the portfolio.
      • Fetches the current price of the cryptocurrency using the get_crypto_price function.
      • Calculates the total cost of the purchase.
      • Checks if the user has sufficient funds.
      • If the asset already exists in the portfolio, updates the quantity. Otherwise, creates a new asset.
      • Creates a new transaction record.
      • Updates the available money in the portfolio.
    • POST /sell: Sells a cryptocurrency asset. Requires authentication.
      • Retrieves the portfolio.
      • Checks if the user has the asset and sufficient quantity to sell.
      • Fetches the current price of the cryptocurrency.
      • Updates the asset quantity or deletes the asset if the quantity reaches zero.
      • Creates a new transaction record.
      • Updates the available money in the portfolio.
    • GET /portfolio: Retrieves the user's portfolio information. Requires authentication.
      • Retrieves the portfolio.
      • Iterates over the assets in the portfolio.
      • Fetches the current price of each cryptocurrency.
      • Calculates the total value of the portfolio.
      • Calculates the absolute and relative performance of the portfolio.
      • Returns the portfolio information, including the available money, total value, performance metrics, and a list of assets with their current prices and quantities.

API Testing (Echo API)

  • Echo API is used to test the API endpoints.
  • The OpenAPI specification (openapi.json) is generated from the FastAPI application and imported into Echo API.
  • Echo API's AI features are used to complete the API documentation and generate test cases.
  • Post-response scripts are used to extract the JWT token from the login response and store it in a global variable.
  • Pre-request scripts are used to add the JWT token to the authorization header of subsequent requests.
  • Automated test cases are created to test multiple endpoints and connect their outputs.
  • Echo API is used to export the API documentation in a user-friendly format.

Front-End Implementation (React and TypeScript)

  • A new directory called "front end" is created for the React project.
  • The React application is created using npm create vite.
  • Cursor is used to generate the front-end code, including components and API service layer.
  • The API service layer (API.ts) defines functions for interacting with the FastAPI backend.
  • The following React components are created:
    • Register: For user registration.
    • Login: For user login.
    • Dashboard or MainInterface: For displaying the portfolio information, buying and selling assets, and adding money.
  • Tailwind CSS is used for styling the components.
  • The front end interacts with the backend API using the functions defined in the API service layer.
  • The JWT token is stored in the browser's local storage or cookies after successful login and used for subsequent requests.

Code Corrections and Improvements

Several issues were identified and corrected during the implementation:

  • JWT Package: The wrong JWT package was initially installed (JWT instead of PyJWT).
  • User Query: The get_current_user function was using payload instead of username to access the username from the JWT token.
  • HTTP Exception: The HTTPException was not properly importing the portfolio attribute.
  • Incorrect Calculation: The initial implementation had an error in the selling and buying logic, treating them as the same type of transaction. This was corrected by using a negative quantity for sell transactions.
  • Zero Division Error: A potential zero division error was fixed in the portfolio performance calculation.
  • Total Cost Calculation: The total cost calculation was incorrect due to using times equals instead of plus equals.
  • Average Purchase Price: The implementation was improved by calculating an average purchase price for assets, which provides more accurate performance tracking.

Conclusion

The video demonstrates how to build a full-stack cryptocurrency demo portfolio application using Python (FastAPI) for the backend and React with TypeScript for the front end. It covers key aspects of backend development, including database design, API implementation, and authentication. It also showcases the use of Echo API for API testing and documentation, and Cursor for accelerating front-end development. The project provides a practical example of how to integrate different technologies to create a complete web application.

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.