Building a Simple Trading Algorithm
Building a simple trading algorithm involves implementing a basic strategy that can generate buy or sell signals based on certain conditions. In this section, we'll walk through an example of a basic trading algorithm implemented in C++.
We'll start by defining a sample price data represented as a vector of double values. This data will simulate the price of a stock over a period of time.
1#include <vector>
2
3using namespace std;
4
5// Define a sample price data
6vector<double> prices = {100.0, 105.0, 98.0, 110.0, 102.0};
Next, we'll initialize variables to keep track of the cash and shares owned. In this example, we'll assume an initial investment of $1000.
1// Initialize variables
2double cash = 1000.0;
3double shares = 0.0;
Now, let's implement a simple moving average crossover strategy. This strategy generates buy signals when the current moving average is higher than the previous moving average, and sell signals when the current moving average is lower than the previous moving average.
1// Implement a simple moving average crossover strategy
2for (int i = 1; i < prices.size(); i++) {
3 double prev_avg = (prices[i - 1] + prices[i - 2]) / 2.0;
4 double curr_avg = (prices[i] + prices[i - 1]) / 2.0;
5
6 // Buy signal
7 if (prev_avg < curr_avg) {
8 shares += cash / prices[i];
9 cash = 0.0;
10 }
11 // Sell signal
12 else if (prev_avg > curr_avg) {
13 cash += shares * prices[i];
14 shares = 0.0;
15 }
16}
Finally, let's print the final portfolio value after executing the trading algorithm.
1// Print the final portfolio value
2cout << "Final portfolio value: $" << cash << endl;
xxxxxxxxxx
}
using namespace std;
int main() {
// Define a sample price data
vector<double> prices = {100.0, 105.0, 98.0, 110.0, 102.0};
// Initialize variables
double cash = 1000.0;
double shares = 0.0;
// Implement a simple moving average crossover strategy
for (int i = 1; i < prices.size(); i++) {
double prev_avg = (prices[i - 1] + prices[i - 2]) / 2.0;
double curr_avg = (prices[i] + prices[i - 1]) / 2.0;
// Buy signal
if (prev_avg < curr_avg) {
shares += cash / prices[i];
cash = 0.0;
}
// Sell signal
else if (prev_avg > curr_avg) {
cash += shares * prices[i];
shares = 0.0;
}
}