【问题标题】:C++ Monitoring variable for changed valueC ++监视变量以更改值
【发布时间】:2013-04-14 02:12:24
【问题描述】:

我正在将 TradeStation EasyLanguage 指标代码转换为 C++ DLL。使用 TradeStation API,可以像这样访问 C++ DLL 中的市场数据:

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

我的问题是:

是否可以在 C++ 中以某种方式“监视”或“监听”变量“currentBarDT”的值何时更改/更新?我想使用值的变化作为触发器来使用 Boost.Signals2 生成信号。

【问题讨论】:

    标签: c++ object state tradestation


    【解决方案1】:

    您可以使用适合您需要的条件变量。

    http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all

    在您更新市场数据的信号中 (i)

    在等待中,你在 i 上放置了一个条件变量(例如是某个水平下的股票)

    如果您需要更多信息,请告诉我,我可以详细说明并使其更明确。

    #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";
          --NbActiveThreads;
    }
    
    void signals()
    {
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            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;
                return;
            }
        }
    
    }
    
    int main()
    {
        NbActiveThreads=3;
        std::thread t1(waits,1,20), t2(waits,2,40), t3(waits,3,95), t4(signals);
        t1.join(); 
        t2.join(); 
        t3.join();
        t4.join();
        return 0;
    }
    

    希望有帮助

    【讨论】:

    • 感谢您的代码。会看的。我计划使用的原则是pELObject-&gt;DateTimeMD[iDataNumber]-&gt;AsDateTime[0]; 指向隐藏在 TradeStation 的 API 中的市场数据 DateTime 值。当该 DateTime 增加时,即时间已经移动了指定的时间间隔,则将广播一个信号以进行进一步的计算。
    • 好的,那么您需要将时间存储在一个变量中(而不是股票价格),并且条件变量将在其上。如果你喜欢这个答案,你能接受吗?这将帮助其他人(并升级我的统计数据:-))
    【解决方案2】:

    您可以创建某种存储类并在调用通知程序中实现operator=。可能适用于模板,但您需要在标题中保留规范。也可以创建类似的接口并覆盖通知器调用。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      相关资源
      最近更新 更多