0bps

Strategy vault / Tools & templates

C API Call Example

Supports C++ 11, compatible with various platforms (Windows/Linux/Mac). Cloud compilation.

Author
Zero
Complexity
Intermediate · 126 lines
Parameters
0

Supports C++ 11, compatible with various platforms (Windows/Linux/Mac). Cloud compilation.

Source C++

void main() {
    if (!Test("c++")) {
        Panic("Please download the latest version of the custodian");
    }
    // json: https://github.com/nlohmann/json
    // All objects returned withValidto determine whether it is valid
    LogProfitReset();
    LogReset();
    Log(_N(9.12345, 2));
    Log("use _C", _C(exchange.GetTicker), _C(exchange.GetAccount));

    // Test asynchronous concurrency
    auto routineTicker = exchange.Go("GetTicker");
    auto routineDepth = exchange.Go("GetDepth");
    Ticker asyncTicker;
    Depth asyncDepth;
    
    // No timeout, Wait Until Ticker Return
    if (routineTicker.wait(asyncTicker)) {
        Log("Wait Ticker OK", asyncTicker.Valid, asyncTicker, asyncTicker.Last);
    } else {
        Log("Wait Ticker fail");
    }
    // Wait with timeout300ms, If specified as0,Return immediately
    if (routineDepth.wait(asyncDepth, 200)) {
        // In waiting timeApiReturn Call, But it does not mean that the depth must be effective., asyncDepth.Valid Represents whether it is valid
        Log("Wait Depth OK", asyncDepth.Valid, asyncDepth);
    } else {
        Log("Wait Depth timeout");
    }
    
    auto records = _C(exchange.GetRecords);
    Log("KLast line of the chart", records[records.size()-1].Time, _D(records[records.size()-1].Time), records[records.size()-1]);
    // Test TA
    auto ema = TA.EMA(records, 20);
    Log("EMALast Few Sets", ema[ema.size()-1], ema[ema.size()-2], ema[ema.size()-3]);
    
    auto macd = talib.MACD(records);
    Log("MACDLast Few Sets", macd[0][macd[0].size()-1], macd[1][macd[1].size()-1], macd[2][macd[2].size()-1]);
        
    //SetErrorFilter("timeout");
    Log(GetOS(), GetPid(), GetLastError(), "MD5", MD5("hello"));
    Log("Hash", Hash("md5", "hex", "hello"), Hash("sha512", "base64", "hello"));
    Log("HMAC", HMAC("sha512", "base64", "hello", "pass"));
    Log(Version(), Unix(), UnixNano());
    Log("Start Test Chart");
    Chart c = Chart(R"EOF({"chart":{"type":"line"},"title":{"text":"Simple Chart"},"xAxis":{"title":{"text":"Date"}},"yAxis":{"title":{"text":"Number"}},"series":[{"name":"number","data":[]}]})EOF");
    c.reset();
    for (size_t i = 0; i < 10; i++) {
        c.add(0, {(Unix() + i)*1000, rand() % 100});
    }
    Log(exchange.GetName(), exchange.GetLabel(), exchanges.size());
    auto acc = exchange.GetAccount();
    if (acc.Valid) {
        Log(acc);
    }
    
    // UseLogStatusCombinejsonDraw a table, Comes with itjsonThe Library is Powerful, For reference:  https://github.com/nlohmann/json
    json tbl = R"({"type" : "table", "title" : "AAA", "cols" : ["Head1", "Head2"], "rows": []})"_json;
    tbl["rows"].push_back({"111", "222"});
    tbl["rows"].push_back({"col2", "col22"});
    LogStatus("`"+tbl.dump()+"`");
    
    auto ticker = exchange.GetTicker();
    if (ticker.Valid) {
        Log(ticker);
        Log(ticker.Info); // InfoStructure is directlyjsonObject
    }
    
    auto d = exchange.GetDepth();
    if (d.Valid) {
        Log(d.Asks[0], d.Bids[0]);
    }
    // Test Futures
    if (exchange.GetName() == "Futures_OKCoin") {
        exchange.SetContractType("this_week");
        exchange.SetMarginLevel(20);
        exchange.SetDirection("closebuy");
            
        auto positions = exchange.GetPosition();
        if (positions.Valid) {
            Log(positions);
        }
    }
    // Test other libraries
    Log("HttpQuery", HttpQuery("http://www.baidu.com/404").size());
    auto obj = json::parse(HttpQuery("http://www.baidu.com/404", "", "", "", true));
    string body = obj["Body"];
    Log("HttpQuery", body.size(), obj["Header"].dump());
    Log(Mail("smtp://smtp.163.com", "[email protected]", "password", "[email protected]", "title", "test c++ email"));
    // Test Dial
    auto client = Dial("tcp://www.baidu.com:80");
    if (client.Valid) {
        client.write("GET / HTTP/1.1\nHost: www.baidu.com\nConnection: Close\n\n");
        while (true) {
            string buf = client.read();
            if (buf == "") {
                break;
            }
            Log("Dial receive", buf.size());
        }
        client.close();
    }

    _G("OK","xxx");
    Log(_G("OK"));
    _G("OK","yyyyyy");
    Log(_G("OK"));
    _G("OK",NULL);
    Log(_G("OK"));
    
    // Test commodity futures 
    if (exchange.GetName() == "Futures_CTP") {
        // C++ IOWhat is returned is ajsonObject
        exchange.IO("mode", 0);
        vector<string> Symbols = {"MA888", "rb888"};
        for (auto &s : Symbols) {
            // C++ SetContractType What is returned is ajsonObject
            Log(s, _C(exchange.SetContractType, s)["InstrumentName"]);
        }
        // Received100Individual/UnittickExit later
        for (size_t i = 0; i < 100; i++) {
            Log(exchange.IO("wait_any"));
        }
    }
}

Published by Zero on the FMZ strategy square · last modified 2018-02-14. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a tested, production-ready module from strategies/C-API-Call-Example.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open