VB Tutor VB2022 VB2019 VB6 VB Sample Code About Us
Stock Trading Simulation

Stock Trading Simulation

Interactive stock trading simulator with VB6 and VB.NET code examples


This stock trading simulation program demonstrates how to create a realistic trading environment using Visual Basic. The application simulates real-time stock market data and allows users to buy and sell shares, track their portfolio, and analyze market trends.

Explore the interactive demo below to experience the simulation, then examine the VB6 and VB.NET code examples to learn how to implement similar functionality in your own applications.

Interactive Stock Trading Simulator

Experience real-time market simulation. Adjust parameters and execute trades!

Market Data

Asking Price (AP)
$15.25
Selling Quantity (SQ)
12,450
Bidding Price (BD)
$15.10
Buying Quantity (BQ)
8,720
Last Done Price (LP)
$15.20
Last Volume
1,200

Your Portfolio

Total Shares
1,000
Average Price (AVP)
$14.80
Buy Value (BV)
$14,800
Market Value (MV)
$15,200
Profit/Loss (P/L)
+$400.00
Available Funds
$5,250.00

Place Trade Order

Code Implementation

Below you'll find the implementation of the stock trading simulation in both VB6 and VB.NET:

' Stock Trading Simulation - VB6
Dim AP As Single  ' Asking Price
Dim SQ As Integer ' Selling Quantity
Dim BD As Single  ' Bidding Price
Dim BQ As Integer ' Buying Quantity
Dim LP As Single  ' Last Done Price
Dim LVOL As Integer ' Last Done Volume
Dim AVP As Single  ' Average Price
Dim TQ As Long    ' Total Quantity (shares)
Dim BV As Single  ' Buy Value
Dim MV As Single  ' Market Value
Dim PL As Single  ' Profit/Loss
Dim OP As Single  ' Order Price
Dim OQ As Long    ' Order Quantity

' Initialize market data
Private Sub Form_Load()
    InitializeMarket
    InitializePortfolio
    Timer1.Interval = 15000 ' Update every 15 seconds
    Timer1.Enabled = True
End Sub

' Generate random market data
Private Sub InitializeMarket()
    Randomize
    AP = Round(Rnd * 2 + 13, 2) ' $13-$15
    SQ = Int(Rnd * 10000) + 1000
    BD = Round(Rnd * 2 + 12.5, 2) ' $12.5-$14.5
    BQ = Int(Rnd * 8000) + 1000
    LP = Round((AP + BD) / 2, 2)
    LVOL = Int(Rnd * 2000) + 500
End Sub

' Initialize portfolio
Private Sub InitializePortfolio()
    TQ = 1000
    AVP = 14.5
    BV = TQ * AVP
    UpdateMarketValue
End Sub

' Update market value and P/L
Private Sub UpdateMarketValue()
    MV = TQ * LP
    PL = MV - BV
End Sub

' Process buy order
Private Sub BuyShares()
    If OP > BD Then ' Order price higher than bid
        ' Calculate new average price
        AVP = (AVP * TQ + OP * OQ) / (TQ + OQ)
        TQ = TQ + OQ
        BV = TQ * AVP
        UpdateMarketValue
    Else
        MsgBox "Order price too low to execute", vbExclamation
    End If
End Sub

' Process sell order
Private Sub SellShares()
    If OP < AP And TQ >= OQ Then ' Order price lower than ask
        ' Calculate new average price
        AVP = (AVP * TQ - OP * OQ) / (TQ - OQ)
        TQ = TQ - OQ
        BV = TQ * AVP
        UpdateMarketValue
    ElseIf TQ < OQ Then
        MsgBox "Not enough shares to sell", vbExclamation
    Else
        MsgBox "Order price too high to execute", vbExclamation
    End If
End Sub

' Timer updates market data periodically
Private Sub Timer1_Timer()
    InitializeMarket
    UpdateMarketValue
    UpdateDisplay
End Sub
' Stock Trading Simulation - VB.NET
Public Class StockTradingForm
    Private AP As Double  ' Asking Price
    Private SQ As Integer ' Selling Quantity
    Private BD As Double  ' Bidding Price
    Private BQ As Integer ' Buying Quantity
    Private LP As Double  ' Last Done Price
    Private LVOL As Integer ' Last Done Volume
    Private AVP As Double  ' Average Price
    Private TQ As Long    ' Total Quantity (shares)
    Private BV As Double  ' Buy Value
    Private MV As Double  ' Market Value
    Private PL As Double  ' Profit/Loss
    
    ' Initialize form
    Private Sub StockTradingForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        InitializeMarket()
        InitializePortfolio()
        ' Set up timer to update every 15 seconds
        Timer1.Interval = 15000
        Timer1.Start()
    End Sub
    
    ' Generate random market data
    Private Sub InitializeMarket()
        Dim rnd As New Random()
        AP = Math.Round(rnd.NextDouble() * 2 + 13, 2) ' $13-$15
        SQ = rnd.Next(1000, 11000)
        BD = Math.Round(rnd.NextDouble() * 2 + 12.5, 2) ' $12.5-$14.5
        BQ = rnd.Next(1000, 9000)
        LP = Math.Round((AP + BD) / 2, 2)
        LVOL = rnd.Next(500, 2500)
    End Sub
    
    ' Initialize portfolio
    Private Sub InitializePortfolio()
        TQ = 1000
        AVP = 14.5
        BV = TQ * AVP
        UpdateMarketValue()
    End Sub
    
    ' Update market value and P/L
    Private Sub UpdateMarketValue()
        MV = TQ * LP
        PL = MV - BV
        ' Update UI components
        lblMarketValue.Text = MV.ToString("C")
        lblProfitLoss.Text = PL.ToString("C")
        lblProfitLoss.ForeColor = If(PL >= 0, Color.Green, Color.Red)
    End Sub
    
    ' Process buy order
    Private Sub BuyShares(price As Double, quantity As Long)
        If price > BD Then ' Order price higher than bid
            ' Calculate new average price
            AVP = (AVP * TQ + price * quantity) / (TQ + quantity)
            TQ += quantity
            BV = TQ * AVP
            UpdateMarketValue()
        Else
            MessageBox.Show("Order price too low to execute", "Trade Error", 
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub
    
    ' Process sell order
    Private Sub SellShares(price As Double, quantity As Long)
        If price < AP AndAlso TQ >= quantity Then
            ' Calculate new average price
            AVP = (AVP * TQ - price * quantity) / (TQ - quantity)
            TQ -= quantity
            BV = TQ * AVP
            UpdateMarketValue()
        ElseIf TQ < quantity Then
            MessageBox.Show("Not enough shares to sell", "Trade Error", 
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            MessageBox.Show("Order price too high to execute", "Trade Error", 
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub
    
    ' Timer updates market data periodically
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        InitializeMarket()
        UpdateMarketValue()
        UpdateUI()
    End Sub
End Class

Stock Trading Algorithm Explained

The stock trading simulation uses these key algorithms:

Market Data Generation

Random values are generated for stock prices and volumes within realistic ranges to simulate market fluctuations.

Average Price Calculation

The average price (AVP) is calculated using the formula:
AVP = (AVP * TQ + OP * OQ) / (TQ + OQ)

Portfolio Updates

Buy and sell orders update the portfolio values including total shares, buy value, and market value.

Profit/Loss Tracking

Real-time P/L is calculated as:
PL = Market Value - Buy Value

Execution Rules:

  • Buy Orders: Execute when order price > current bidding price
  • Sell Orders: Execute when order price < current asking price and sufficient shares available
  • Market Updates: Prices and volumes change at regular intervals (every 15 seconds)

Key Features of the Simulation

Real-time Market Simulation

Continuously updated stock prices and trading volumes that mimic real market behavior

Portfolio Tracking

Automatic calculation of average price, market value, and profit/loss

Trade Execution Logic

Realistic buy/sell order processing based on market conditions

Historical Data

Price chart visualization showing market trends over time