Question

PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks...

PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA:

1.)Read your stocks from your mystocks.txt file. You can use this information for the simulator.

2.)The stock price simulator will return the current price of the stock. The current prices is the prices of the requested ticker + a random number.

3.)We will assume that the stock price remains constant after the price check till your trade gets executed. Therefore, a buy or a sell order placed will be assumed to be executed at the price returned at the time of price check (called quote).

4.)The application will be able to facilitate purchase and sale of a stock.

5.)The application will be user oriented and will keep a record of the five stocks the user owns, allow the user to buy more shares, and sell shares of only those stocks.

6.)The application will also maintain the balance of money the user has deposited from which to buy stocks. Initial balance can be $20,000. When the user buys shares, the cost is taken out of this balance. When the user sells, the proceeds are returned to this balance.

7.)The application should save all the information in a file called “portfolio.txt” when the application closes it saves. It loads the information from that same file when the application starts if the file exists. File does not exist, the application will assume that the user has never traded before.

8.)Test your functions to make sure that you can make at least 20 trades

*************************************MY TEST CODE **************************************************

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <string.h>

#define RANGE 10

#define MAX_MY_STOCKS 5

#define CAPACITY 5

typedef struct {

char ticker[10];

double price;

} StockPrice;

typedef struct {

char ticker[10];

double shares;

} Stock;

typedef struct {

Stock myStocks[MAX_MY_STOCKS]; // MAX_MY_STOCKS is five.

double balance;

} Portfolio;

void initializeSimulator(char* fileName, StockPrice* pMyStocks, int* pMyStocksSize);

StockPrice* findStockPrice(StockPrice* pMyStocks, int myStocksSize, char* ticker);

double priceSimulator(StockPrice* pMyStocks, int myStocksSize, char* ticker);

void initializePortfolio(char* fileName, Portfolio* myPortfolio, double balance, Stock* myStock)

{

FILE* pFile = 0;

pFile = fopen(fileName, "r");

int capacity = 0, throwAway = 0;

if (pFile == NULL) {

printf("File did not open\n");

return;

}

while (fscanf(pFile, "%s %lf", myStock[(capacity)].ticker, throwAway) != EOF) {

myStock[(capacity)].shares = 0;

(capacity)++;

if (capacity >= CAPACITY) return;

}

if (pFile) fclose(pFile);

}

void initializeSimulator(char* fileName, StockPrice* pMyStocks, int* pMyStocksSize) {

FILE* pFile = 0;

pFile = fopen(fileName, "r");

*pMyStocksSize = 0;

if (pFile == NULL) {

printf("File did not open\n");

return;

}

while (fscanf(pFile, "%s %lf", pMyStocks[(*pMyStocksSize)].ticker, &(pMyStocks[(*pMyStocksSize)].price)) != EOF) {

(*pMyStocksSize)++;

if (*pMyStocksSize >= CAPACITY) return;

}

if (pFile) fclose(pFile);

}

double priceSimulatorInternal(double price) {

double perturbation = 1 / price;

double multiplier;

multiplier = ((double)rand()) / RAND_MAX*perturbation;

multiplier -= perturbation / 2;

multiplier += 1;

return multiplier*price;

}

//This function finds the stock corresponding to the ticker symbol provided and

//return the pointer to that StockPrice struct.

StockPrice* findStockPrice(StockPrice* pMyStocks, int myStocksSize, char* ticker) {

int i;

for (i = 0; i<myStocksSize; i++) {

if (!strcmp(pMyStocks[i].ticker, ticker)) {

return &pMyStocks[i];

}

}

return 0;

}

//This function allows user to obtain the current price of a specific stock by

//typing in the ticker. The new price is also saved in the myStocks for that stock.

//This function can only be called after a call to initalizeSimulator() specified above.

double priceSimulator(StockPrice* pMyStocks, int myStocksSize, char* ticker) {

StockPrice* pStockPrice;

double newPrice;

pStockPrice = findStockPrice(pMyStocks, myStocksSize, ticker);

newPrice = priceSimulatorInternal(pStockPrice->price);

pStockPrice->price = newPrice;

return newPrice;

}

void printStockPrices(StockPrice* pMyStocks, int myStocksSize) {

int i;

printf("\n myStocks[]\n");

for (i = 0; i<myStocksSize; i++)

{

printf("Ticker=%s; Price=%lf\n", pMyStocks[i].ticker, pMyStocks[i].price);

}

}

void test() {

int i;

double p = 103.45;

StockPrice* pStockPrice;

StockPrice myStocks[MAX_MY_STOCKS];

int myStocksSize;

Stock myStock[MAX_MY_STOCKS];

Portfolio* myPortfolio[MAX_MY_STOCKS];

double newPrice, balance =0;

srand(time(0));

//Test for initializeSimulator()

initializeSimulator("mystocks.txt", myStocks, &myStocksSize, MAX_MY_STOCKS);

for (i = 0; i<myStocksSize; i++) {

printf("Ticker=%s; Price=%lf\n", myStocks[i].ticker, myStocks[i].price);

}

//Test for initaialize a portfolio()

initializePortfolio("mystocks.txt", myPortfolio, balance, myStock);

for (int i = 0; i<MAX_MY_STOCKS; i++)

{

printf("Ticker=%s; Shares=%lf\n", myStock[i].ticker, myStock[i].shares);

}

char again = 'y';

do

{

int answer;

printf("Welcome to my stock market simulation program\n");

printf("Please enter a number to select a menu option\n");

printf("1.) View a single stock price\n");

printf("2.) View all of the stock prices\n");

printf("3.) View a portfolio\n");

printf("4.) Buy a stock\n");

printf("5.) Sell a stock\n");

printf("6.) Update\n");

printf("7.) Quit\n");

scanf("%d", &answer);

switch (answer)

{

case 1:

{

char myTicker[4];

char *tick = &myTicker;

printf("Please enter the ticker of the stock you would look to see:");

scanf(" %s", &myTicker);

printf("%s", myTicker);

printf("\nTesting findStockPrice()\n");

pStockPrice = findStockPrice(myStocks, myStocksSize, tick);

if (pStockPrice) {

printf("Ticker=%s; Price=%lf\n", pStockPrice->ticker, pStockPrice->price);

}

else {

printf("Ticker Not found\n");

}

break;

}

case 2:

{

printStockPrices(myStocks, myStocksSize);

break;

}

case 3:

{

}

case 4:

{

}

case 5:

{

}

case 6:

{

}

case 7:

{

again = 'n';

break;

}

}

} while (again == 'y');

system("pause");

}

int main(void) {

test();

return 0;

}

/*

//Testing findStockPrice()

printf("\nTesting findStockPrice()\n");

pStockPrice = findStockPrice(myStocks, myStocksSize,"AEIS");

if(pStockPrice) {

printf("Ticker=%s; Price=%lf\n",pStockPrice->ticker,pStockPrice->price);

}else{

printf("Ticker Not found\n");

}

//Testing priceSimulator()

printf("\nTesting priceSimulator()\n");

for( i=0;i<6;i++) {

//multiplier = ((double) rand())/RAND_MAX*pertubation -pertubation/2+1;

//price = priceSimulatorInternal(p);

newPrice = priceSimulator(myStocks,myStocksSize, "ATVI");

printf("\n-->%lf\n",newPrice);

printStockPrices(myStocks,myStocksSize);

}

*/

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define RANGE 10
#define MAX_MY_STOCKS 5
#define CAPACITY 5

typedef struct 
{
    char ticker[RANGE];
    double price;
} StockPrice;

typedef struct 
{
    char ticker[RANGE];
    int shares;
} Stock;

typedef struct 
{
    Stock myStocks; // MAX_MY_STOCKS is five.
} Portfolio;

int initializeSimulator(char* fileName, StockPrice* pMyStocks, int* pMyStocksSize);
StockPrice* findStockPrice(StockPrice* pMyStocks, int myStocksSize, char* ticker);
double priceSimulator(StockPrice* pMyStocks, int myStocksSize, char* ticker);

int initializePortfolio(const char *fileName, Portfolio *myPortfolio, int *myPortfolioSize)
{
    FILE* pFile = 0;
    pFile = fopen(fileName, "r");
    if (pFile == NULL)
    {
        printf("File did not open\n");
        return 0;
    }
    while (fscanf(pFile, "%s %d", myPortfolio[*myPortfolioSize].myStocks.ticker, &myPortfolio[*myPortfolioSize].myStocks.shares) != EOF)
    {
        (*myPortfolioSize)++;
        if (*myPortfolioSize >= CAPACITY)
        {
            fclose(pFile);
            return 1;
        }
    }
    fclose(pFile);
}

int initializeSimulator(const char* fileName, StockPrice* pMyStocks, int* pMyStocksSize)
{
    FILE* pFile = 0;
    pFile = fopen(fileName, "r");
    *pMyStocksSize = 0;
    if (pFile == NULL)
    {
        printf("File did not open\n");
        return 0;
    }
    while (fscanf(pFile, "%s %lf", pMyStocks[(*pMyStocksSize)].ticker, &(pMyStocks[(*pMyStocksSize)].price)) != EOF)
    {
        (*pMyStocksSize)++;
        if (*pMyStocksSize >= CAPACITY)
        {
            fclose(pFile);
            return 1;
        }
    }
    fclose(pFile);
}

double priceSimulatorInternal(double price)
{
    double perturbation = 1 / price;
    double multiplier;
    multiplier = ((double)rand()) / RAND_MAX * perturbation;
    multiplier -= perturbation / 2;
    multiplier += 1;
    return multiplier * price;
}

//This function finds the stock corresponding to the ticker symbol provided and
//return the pointer to that StockPrice struct.
StockPrice* findStockPrice(StockPrice* pMyStocks, int myStocksSize, char* ticker)
{
    int i;
    for (i = 0; i<myStocksSize; i++)
    {
        if (!strcmp(pMyStocks[i].ticker, ticker))
        {
            return &pMyStocks[i];
        }
    }
    return 0;
}

//This function allows user to obtain the current price of a specific stock by
//typing in the ticker. The new price is also saved in the myStocks for that stock.
//This function can only be called after a call to initalizeSimulator() specified above.
double priceSimulator(StockPrice* pMyStocks, int myStocksSize, char* ticker)
{
    StockPrice* pStockPrice;
    double newPrice;
    pStockPrice = findStockPrice(pMyStocks, myStocksSize, ticker);
    newPrice = priceSimulatorInternal(pStockPrice->price);
    pStockPrice->price = newPrice;
    return newPrice;
}

void printStockPrices(StockPrice* pMyStocks, int myStocksSize)
{
    int i;
    printf("\n Current Stock Prices\n");
    for (i = 0; i<myStocksSize; i++)
    {
        printf("Ticker=%s; Price=$%.2lf\n", pMyStocks[i].ticker, pMyStocks[i].price);
    }
}

//Function to find portfolio for a ticker
void findPortfolio(Portfolio* myPortfolio, int myPortfolioSize)
{
    char ticker[RANGE];
    printf("Enter ticker: ");
    scanf("%s", ticker);
    for (int i = 0; i < myPortfolioSize; i++)
    {
        if (strcmp(myPortfolio[i].myStocks.ticker, ticker) == 0)
        {
            printf("Ticker: %s Shares: %d\n", ticker, myPortfolio[i].myStocks.shares);
            return;
        }
    }
    printf("Ticker not found\n");
    return;
}

//Function to buy stocks
void buyStock(StockPrice* myStockPrice, int myStockSize, Portfolio* myPortfolio, int* myPortfolioSize, double *balance)
{
    char ticker[RANGE];
    int shares;
    //Update price of every stocks using price simulator
    for (int i = 0; i < myStockSize; i++)
    {
        myStockPrice[i].price = priceSimulator(myStockPrice, myStockSize, myStockPrice[i].ticker);
    }
    printStockPrices(myStockPrice, myStockSize);
    printf("Current Balance: $%lf\n", *balance);
    printf("\nEnter ticker to buy shares: ");
    scanf("%s", ticker);
    for (int i = 0; i < myStockSize; i++)
    {
        if (strcmp(myStockPrice[i].ticker, ticker) == 0)
        {
            printf("Enter how many shares you want to buy: ");
            scanf("%d", &shares);
            if (*balance >= shares*myStockPrice[i].price)
            {
                *balance -= shares * myStockPrice[i].price;
                for (int j = 0; j < *myPortfolioSize; j++)
                {
                    if (strcmp(myPortfolio[j].myStocks.ticker, ticker) == 0)
                    {
                        myPortfolio[j].myStocks.shares += shares;
                        //printf("Balance: %lf, shares in %s = %d", balance, myPortfolio[i ,myPortfolio[i].myStocks.shares);
                        return;
                    }
                }
                strcpy(myPortfolio[*myPortfolioSize].myStocks.ticker, ticker);
                myPortfolio[*myPortfolioSize].myStocks.shares = shares;
                (*myPortfolioSize)++;
            }
            else
            {
                printf("You don't have enough money to buy shares\n");
            }
            return;
        }
    }
    printf("Ticker not found\n");
}

//Function to sell stocks
void sellStock(StockPrice* myStockPrice, int myStockSize, Portfolio* myPortfolio, int* myPortfolioSize, double *balance)
{
    char ticker[RANGE];
    int shares;
    //Update price of every stocks using price simulator
    for (int i = 0; i < myStockSize; i++)
    {
        myStockPrice[i].price = priceSimulator(myStockPrice, myStockSize, myStockPrice[i].ticker);
    }
    printStockPrices(myStockPrice, myStockSize);
    printf("Current Balance: $%lf\n", *balance);
    printf("\nEnter ticker to sell shares: ");
    scanf("%s", ticker);
    for (int i = 0; i < *myPortfolioSize; i++)
    {
        if (strcmp(myPortfolio[i].myStocks.ticker, ticker) == 0)
        {
            printf("Ticker: %s; Shares: %d\n", ticker, myPortfolio[i].myStocks.shares);
            printf("Enter how many shares you want to sell: ");
            scanf("%d", &shares);
            if (myPortfolio[i].myStocks.shares >= shares)
            {
                for (int j = 0; j < myStockSize; j++)
                {
                    if (strcmp(myStockPrice[j].ticker, ticker) == 0)
                    {
                        myPortfolio[i].myStocks.shares -= shares;
                        *balance += shares * myStockPrice[j].price;
                        return;
                    }
                }
            }
            else
            {
                printf("You don't have enough shares to sell\n");
            }
            return;
        }
    }
    printf("Ticker not found\n");
}

//Function to save all information in portfolio.txt
void update(Portfolio* myPortfolio, int myPortfolioSize)
{
    FILE* f = fopen("portfolio.txt", "w");
    if (f == NULL)
    {
        printf("Cannot open file\n");
        return;
    }
    for (int i = 0; i < myPortfolioSize; i++)
    {
        fprintf(f, "%s %d\n", myPortfolio[i].myStocks.ticker, myPortfolio[i].myStocks.shares);
    }
    fclose(f);
}

void test()
{
    int i;
    double p = 103.45;
    StockPrice* pStockPrice;
    StockPrice myStocks[MAX_MY_STOCKS];
    int myStocksSize=0, myPortfolioSize=0;
    Stock myStock[MAX_MY_STOCKS];
    Portfolio myPortfolio[MAX_MY_STOCKS];
    double newPrice, balance = 20000;
    srand(time(NULL));
    //Test for initializeSimulator()
    initializeSimulator("mystocks.txt", myStocks, &myStocksSize);
    //Test for initaialize a portfolio()
    initializePortfolio("portfolio.txt", myPortfolio, &myPortfolioSize);
    char again = 'y';
    do
    {
        int answer;
        printf("Welcome to my stock market simulation program\n");
        printf("Please enter a number to select a menu option\n");
        printf("1.) View a single stock price\n");
        printf("2.) View all of the stock prices\n");
        printf("3.) View a portfolio\n");
        printf("4.) Buy a stock\n");
        printf("5.) Sell a stock\n");
        printf("6.) Update\n");
        printf("7.) Quit\n");
        scanf("%d", &answer);
        switch (answer)
        {
            case 1:
            {
                char myTicker[13];
                char *tick = myTicker;
                printf("Please enter the ticker of the stock you would look to see:");
                scanf(" %s", myTicker);
                printf("%s", myTicker);
                printf("\nTesting findStockPrice()\n");
                pStockPrice = findStockPrice(myStocks, myStocksSize, tick);
                if (pStockPrice)
                {
                    printf("Ticker=%s; Price=%lf\n", pStockPrice->ticker, pStockPrice->price);
                }
                else
                {
                    printf("Ticker Not found\n");
                }
                break;
            }
            
            case 2:
            {
                printStockPrices(myStocks, myStocksSize);
                break;
            }
            
            case 3:
            {
                findPortfolio(myPortfolio, myPortfolioSize);
                break;
            }
            
            case 4:
            {
                buyStock(myStocks, myStocksSize, myPortfolio, &myPortfolioSize, &balance);
                break;
            }
    
            case 5:
            {
                sellStock(myStocks, myStocksSize, myPortfolio, &myPortfolioSize, &balance);
                break;
            }
    
            case 6:
            {
                update(myPortfolio, myPortfolioSize);
                break;
            }
    
            case 7:
            {
                again = 'n';
                update(myPortfolio, myPortfolioSize);
                break;
            }
        }
    } while (again == 'y');
    system("pause");
}

int main(void)
{
    test();
    return 0;
}

Example Output:

Add a comment
Know the answer?
Add Answer to:
PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I JUST NEED HELP WITH DISPLAY PART! please help! thanks in advance // This function saves...

    I JUST NEED HELP WITH DISPLAY PART! please help! thanks in advance // This function saves the array of structures to file. It is already implemented for you. // You should understand how this code works so that you know how to use it for future assignments. void save(char* fileName) { FILE* file; int i; file = fopen(fileName, "wb"); fwrite(&count, sizeof(count), 1, file); for (i = 0; i < count; i++) { fwrite(list[i].name, sizeof(list[i].name), 1, file); fwrite(list[i].class_standing, sizeof(list[i].class_standing), 1, file);...

  • Hi there! I need to fix the errors that this code is giving me and also...

    Hi there! I need to fix the errors that this code is giving me and also I neet to make it look better. thank you! #include <iostream> #include <windows.h> #include <ctime> #include <cstdio> #include <fstream> // file stream #include <string> #include <cstring> using namespace std; const int N=10000; int *freq =new int [N]; int *duration=new int [N]; char const*filename="filename.txt"; int songLength(140); char MENU(); // SHOWS USER CHOICE void execute(const char command); void About(); void Save( int freq[],int duration[],int songLength); void...

  • // Write the compiler used: Visual studio // READ BEFORE YOU START: // You are given...

    // Write the compiler used: Visual studio // READ BEFORE YOU START: // You are given a partially completed program that creates a list of patients, like patients' record. // Each record has this information: patient's name, doctor's name, critical level of patient, room number. // The struct 'patientRecord' holds information of one patient. Critical level is enum type. // An array of structs called 'list' is made to hold the list of patients. // To begin, you should trace...

  • Pease help ASAP C programming course. Cannot use global variables. This is the assignment: In this...

    Pease help ASAP C programming course. Cannot use global variables. This is the assignment: In this project you will calculate the maximum profit you could have made by trading a single stock over a period of one month. You will assume that you bought rounded stock units (usually in hundreds, or tens) worth between $3000 and $5000 at the best possible“closing” price during the period and sold it at the best possible “closing” price. You will assume that you are...

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • Hello! I'm posting this program that is partially completed if someone can help me out, I...

    Hello! I'm posting this program that is partially completed if someone can help me out, I will give you a good rating! Thanks, // You are given a partially completed program that creates a list of employees, like employees' record. // Each record has this information: employee's name, supervisors's name, department of the employee, room number. // The struct 'employeeRecord' holds information of one employee. Department is enum type. // An array of structs called 'list' is made to hold...

  • Help with my code: The code is suppose to read a text file and when u...

    Help with my code: The code is suppose to read a text file and when u enter the winning lotto number it suppose to show the winner without the user typing in the other text file please help cause when i enter the number the code just end without displaying the other text file #include <stdio.h> #include <stdlib.h> typedef struct KnightsBallLottoPlayer{ char firstName[20]; char lastName[20]; int numbers[6]; }KBLottoPlayer; int main(){ //Declare Variables FILE *fp; int i,j,n,k; fp = fopen("KnightsBall.in","r"); //...

  • Need this in C The starter code is long, if you know how to do it...

    Need this in C The starter code is long, if you know how to do it in other way please do. Do the best you can please. Here's the starter code: // ----------------------------------------------------------------------- // monsterdb.c // ----------------------------------------------------------------------- #include #include #include // ----------------------------------------------------------------------- // Some defines #define NAME_MAX 64 #define BUFFER_MAX 256 // ----------------------------------------------------------------------- // Structs typedef struct { char name[NAME_MAX]; int hp; int attackPower; int armor; } Character; typedef struct { int size; Character *list; } CharacterContainer; // ----------------------------------------------------------------------- //...

  • Hardware Inventory – Write a database to keep track of tools, their cost and number. Your...

    Hardware Inventory – Write a database to keep track of tools, their cost and number. Your program should initialize hardware.dat to 100 empty records, let the user input a record number, tool name, cost and number of that tool. Your program should let you delete and edit records in the database. The next run of the program must start with the data from the last session. This is my program so far, when I run the program I keep getting...

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT