#include #include #include #include // need for rand() #include // need for rand() using namespace std; static double cash = 1000.00, stockPrice = 10.0, expectedPrice; static int stockShares; const bool DEBUG_first_five = true; // debugging for the first five iteration const bool DEBUG_every_1000 = false; // debugging for every 1000th iteration int DEBUG_counter = 0; void main() { srand(time(NULL)); cout << fixed << showpoint << setprecision(2); bool keepTrading = true; while (keepTrading) { // debug for loop if (DEBUG_first_five) { DEBUG_counter++; cout << "[" << DEBUG_counter << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } if (DEBUG_every_1000) { DEBUG_counter++; if (DEBUG_counter % 1000 == 0) cout << "[" << DEBUG_counter << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } stockPrice = stockPrice + static_cast(rand()-RAND_MAX/2)/RAND_MAX; if (stockPrice <= 0) stockPrice = 0.02; expectedPrice = stockPrice + static_cast(rand()-RAND_MAX/2)/RAND_MAX; if (cash > stockPrice && expectedPrice > stockPrice*1.01) { cash = cash - stockPrice; stockShares = stockShares + 1; // debug for buy if (DEBUG_first_five) { cout << "[buy" << stockShares << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } if (DEBUG_every_1000) { if (DEBUG_counter % 1000 == 0) cout << "[buy" << stockShares << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } } if (stockShares > 0 && expectedPrice*1.02 < stockPrice) { cash = cash + stockPrice; stockShares = stockShares - 1; // debug for sell if (DEBUG_first_five) { cout << "[sell" << stockShares << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } if (DEBUG_every_1000) { if (DEBUG_counter % 1000 == 0) cout << "[sell" << stockShares << "]: " << "cash = " << cash << "; stockShares = " << stockShares << "; stockPrice = " << stockPrice << "; value = " << (cash+stockShares*stockPrice) << endl; } } if (cash+stockShares*stockPrice == 500) keepTrading = false; if (cash+stockShares*stockPrice == 2000) keepTrading = false; // loop controller for debug if (DEBUG_first_five && DEBUG_counter == 5) keepTrading = false; if (DEBUG_every_1000 && DEBUG_counter == 5000) keepTrading = false; } // end while cout << "You now have $" << (cash+stockShares*stockPrice) << endl; }