GoFaster GoFaster -4 years ago 132
C++ Question

C++ Monitoring variable for changed value

I'm converting a TradeStation EasyLanguage indicator code to a C++ DLL. Using the TradeStation API it's possible to access market data in the C++ DLL like so:

double currentBarDT = pELObject->DateTimeMD[iDataNumber]->AsDateTime[0];

My question is:

Is it possible in C++ to somehow 'watch' or 'listen' for when the variable 'currentBarDT' has its value changed/updated? I would like to use the changing of the value as a trigger to generate a signal with Boost.Signals2.

Answer Source

You can use condition variable that fit your need.


in the signals you update your market data (i)

in the wait you put a condition variable on i (is the stock under a certain level for example)

Tell me if you need more info I can detail and make it more explicit.

#include <stdlib.h>     /* srand, rand */
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <atomic>
std::condition_variable cv;
std::mutex cv_m;
double StockPrice;//price of the stock
std::atomic<int> NbActiveThreads=0;//count the number of active alerts to the stock market

void waits(int ThreadID, int PriceLimit)
      std::unique_lock<std::mutex> lk(cv_m);
      cv.wait(lk, [PriceLimit]{return StockPrice >PriceLimit ;});
      std::cerr << "Thread "<< ThreadID << "...Selling stock.\n";

void signals()
    while (true)
        std::cerr << "GettingPrice "<<std::endl;
        std::unique_lock<std::mutex> lk(cv_m);
        /* generate secret number between 1 and 10: */
        StockPrice = rand() % 100 + 1;  
        std::cerr << "Price =" << StockPrice << std::endl;
        cv.notify_all();//updates the price and sell all the stocks if needed
        if (NbActiveThreads==0)
            std::cerr <<"No more alerts "<<std::endl;


int main()
    std::thread t1(waits,1,20), t2(waits,2,40), t3(waits,3,95), t4(signals);
    return 0;

Hope that helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download