C API Reference

TechKit provides a stable C ABI for maximum cross-language compatibility.

Header Files

#include <techkit/techkit_c.h>

Data Types

Result Structures

tk_result

Single-value indicator result.

typedef struct {
    double value;   // Calculated value
    int valid;      // 1 = valid, 0 = warmup period
} tk_result;

Usage:

tk_result r = tk_update(ind, price);
if (r.valid) {
    printf("Value: %.4f\n", r.value);
}

tk_macd_result

MACD indicator result with three outputs.

typedef struct {
    double macd;        // MACD line (fast EMA - slow EMA)
    double signal;      // Signal line (EMA of MACD)
    double histogram;   // Histogram (MACD - Signal)
    int valid;
} tk_macd_result;

tk_bbands_result

Bollinger Bands result.

typedef struct {
    double upper;   // Upper band (middle + nbdev * stddev)
    double middle;  // Middle band (SMA)
    double lower;   // Lower band (middle - nbdev * stddev)
    int valid;
} tk_bbands_result;

tk_stoch_result

Stochastic oscillator result.

typedef struct {
    double slowk;   // %K line (smoothed)
    double slowd;   // %D line (SMA of %K)
    int valid;
} tk_stoch_result;

tk_adx_result

ADX indicator result with three outputs.

typedef struct {
    double plus_di;     // +DI (Plus Directional Indicator)
    double minus_di;    // -DI (Minus Directional Indicator)
    double adx;         // ADX (Average Directional Index)
    int valid;
} tk_adx_result;

tk_stochf_result

Fast Stochastic result.

typedef struct {
    double k;       // %K line (raw stochastic)
    double d;       // %D line (SMA of %K)
    int valid;
} tk_stochf_result;

tk_stochrsi_result

Stochastic RSI result.

typedef struct {
    double k;       // %K line (smoothed stochastic of RSI)
    double d;       // %D line (SMA of %K)
    int valid;
} tk_stochrsi_result;

tk_aroon_result

Aroon indicator result.

typedef struct {
    double up;      // Aroon Up (0-100)
    double down;    // Aroon Down (0-100)
    int valid;
} tk_aroon_result;

tk_minmax_result

MINMAX indicator result.

typedef struct {
    double min;     // Minimum value over period
    double max;     // Maximum value over period
    int valid;
} tk_minmax_result;

tk_ht_phasor_result

Hilbert Transform Phasor result.

typedef struct {
    double inphase;     // InPhase component (I1)
    double quadrature;  // Quadrature component (Q1)
    int valid;
} tk_ht_phasor_result;

tk_ht_sine_result

Hilbert Transform Sine result.

typedef struct {
    double sine;        // Sine of dominant cycle phase
    double leadsine;    // LeadSine (45 degrees ahead)
    int valid;
} tk_ht_sine_result;

tk_drawdown_result

Drawdown Series result.

typedef struct {
    double drawdown;      // Current drawdown (negative value)
    double max_drawdown;  // Maximum drawdown (negative value)
    int duration;         // Current drawdown duration in bars
    int max_duration;     // Maximum drawdown duration in bars
    int valid;
} tk_drawdown_result;

tk_zigzag_result

ZigZag indicator result.

typedef struct {
    double zigzag_value;      // Current ZigZag line value (extreme price)
    int direction;            // Current trend: 1=up, -1=down, 0=undefined
    int is_pivot;             // 1 if pivot confirmed this bar, 0 otherwise
    int pivot_type;           // If is_pivot: 1=swing high, -1=swing low
    double last_pivot_price;  // Price of most recent confirmed pivot
    int bars_since_pivot;     // Bars since last confirmed pivot
    int valid;
} tk_zigzag_result;

tk_swing_result

Swing High/Low detector result.

typedef struct {
    int is_swing_high;        // 1 if swing high detected, 0 otherwise
    int is_swing_low;         // 1 if swing low detected, 0 otherwise
    double swing_high_price;  // Price of swing high (or 0 if not detected)
    double swing_low_price;   // Price of swing low (or 0 if not detected)
    int bars_ago;             // How many bars ago the swing occurred
    int valid;
} tk_swing_result;

tk_pivot_result

Pivot Points result.

typedef struct {
    double pp;                // Pivot Point
    double r1, r2, r3;        // Resistance levels 1, 2, 3
    double s1, s2, s3;        // Support levels 1, 2, 3
    int valid;
} tk_pivot_result;

tk_harmonic_result

Harmonic Pattern detection result.

typedef struct {
    tk_harmonic_type pattern;   // Detected pattern type
    int direction;              // 1=bullish, -1=bearish, 0=none
    double x_price, a_price, b_price, c_price, d_price;  // XABCD point prices
    int x_bar, a_bar, b_bar, c_bar, d_bar;               // XABCD point bar indices
    double xab_ratio, abc_ratio, bcd_ratio, xad_ratio;    // Fibonacci ratios
    double prz_high, prz_low;   // Potential Reversal Zone
    double score;                // Pattern quality score (0-100)
    int is_complete;             // 1 if D point is confirmed
    int valid;
} tk_harmonic_result;

tk_chart_pattern_result

Chart Pattern detection result.

typedef struct {
    tk_chart_pattern_type pattern;  // Detected pattern type
    int direction;                  // 1=bullish, -1=bearish, 0=neutral
    double neckline;                // Neckline/support/resistance level
    double neckline_slope;          // Slope of neckline (per bar)
    double target_price;            // Projected target after breakout
    double point_prices[5];         // Prices of key pivot points
    int point_bars[5];               // Bar indices of key points
    int num_points;                  // Number of valid points (3-5)
    double height;                   // Pattern height
    double width_bars;               // Pattern width in bars
    double symmetry_score;           // Symmetry quality (0-1)
    double score;                    // Overall quality score (0-100)
    int is_complete;                 // 1 if pattern formation complete
    int is_confirmed;                // 1 if breakout confirmed
    double breakout_price;           // Price at breakout (if confirmed)
    int valid;
} tk_chart_pattern_result;

tk_ohlcv

OHLCV bar data for indicators requiring full price bar.

typedef struct {
    double open;
    double high;
    double low;
    double close;
    double volume;
} tk_ohlcv;

Opaque Handle

typedef struct tk_indicator_s* tk_indicator;

All indicator instances are represented by opaque handles. This ensures:

  • ABI stability across versions

  • Memory safety (internal state hidden)

  • Thread safety (no shared state)

Error Codes

typedef enum {
    TK_OK = 0,                      // Success
    TK_ERR_INVALID_PARAM = -1,      // Invalid parameter value
    TK_ERR_NOT_ENOUGH_DATA = -2,    // Not enough data for operation
    TK_ERR_OUT_OF_MEMORY = -3,      // Memory allocation failed
    TK_ERR_NULL_POINTER = -4,       // Null pointer passed
    TK_ERR_INVALID_HANDLE = -5      // Invalid indicator handle
} tk_error;

Moving Average Type

typedef enum {
    TK_MA_SMA   = 0,    // Simple Moving Average
    TK_MA_EMA   = 1,    // Exponential Moving Average
    TK_MA_WMA   = 2,    // Weighted Moving Average
    TK_MA_DEMA  = 3,    // Double Exponential Moving Average
    TK_MA_TEMA  = 4,    // Triple Exponential Moving Average
    TK_MA_TRIMA = 5,    // Triangular Moving Average
    TK_MA_KAMA  = 6,    // Kaufman Adaptive Moving Average
    TK_MA_MAMA  = 7,    // MESA Adaptive Moving Average (not implemented)
    TK_MA_T3    = 8     // Triple Exponential Moving Average (T3)
} tk_ma_type;

Pivot Point Type

typedef enum {
    TK_PIVOT_CLASSIC = 0,     // Classic: PP=(H+L+C)/3
    TK_PIVOT_FIBONACCI = 1,   // Fibonacci: uses 0.382, 0.618, 1.0 ratios
    TK_PIVOT_WOODIE = 2,      // Woodie: PP=(H+L+2C)/4
    TK_PIVOT_CAMARILLA = 3,   // Camarilla: close-based with 1.1/12, 1.1/6, 1.1/4
    TK_PIVOT_DEMARK = 4       // DeMark: X varies by close vs open relationship
} tk_pivot_type;

Harmonic Pattern Type

typedef enum {
    TK_HARMONIC_NONE = 0,
    TK_HARMONIC_GARTLEY_BULL = 1,
    TK_HARMONIC_GARTLEY_BEAR = 2,
    TK_HARMONIC_BUTTERFLY_BULL = 3,
    TK_HARMONIC_BUTTERFLY_BEAR = 4,
    TK_HARMONIC_BAT_BULL = 5,
    TK_HARMONIC_BAT_BEAR = 6,
    TK_HARMONIC_CRAB_BULL = 7,
    TK_HARMONIC_CRAB_BEAR = 8,
    TK_HARMONIC_SHARK_BULL = 9,
    TK_HARMONIC_SHARK_BEAR = 10,
    TK_HARMONIC_CYPHER_BULL = 11,
    TK_HARMONIC_CYPHER_BEAR = 12
} tk_harmonic_type;

Chart Pattern Type

typedef enum {
    TK_CHART_NONE = 0,
    TK_CHART_HEAD_SHOULDERS = 1,
    TK_CHART_INV_HEAD_SHOULDERS = 2,
    TK_CHART_DOUBLE_TOP = 3,
    TK_CHART_DOUBLE_BOTTOM = 4,
    TK_CHART_TRIPLE_TOP = 5,
    TK_CHART_TRIPLE_BOTTOM = 6,
    TK_CHART_TRIANGLE_SYM = 7,
    TK_CHART_TRIANGLE_ASC = 8,
    TK_CHART_TRIANGLE_DESC = 9,
    TK_CHART_WEDGE_RISING = 10,
    TK_CHART_WEDGE_FALLING = 11
} tk_chart_pattern_type;

Lifecycle Functions

Creating Indicators

All indicators are created using factory functions with the pattern tk_<name>_new(...). These functions return an opaque handle (tk_indicator) or NULL on error.

Moving Averages (Overlap Studies)

Function

Parameters

Input

Output

Lookback

tk_sma_new(period)

period: int

close

single

period-1

tk_ema_new(period)

period: int

close

single

period-1

tk_wma_new(period)

period: int

close

single

period-1

tk_dema_new(period)

period: int

close

single

2*(period-1)

tk_tema_new(period)

period: int

close

single

3*(period-1)

tk_kama_new(period)

period: int

close

single

period

tk_trima_new(period)

period: int

close

single

period-1

tk_t3_new(period, vfactor)

period: int, vfactor: double

close

single

6*(period-1)

tk_ma_new(period, type)

period: int, type: tk_ma_type

close

single

varies

tk_bbands_new(period, nbdevup, nbdevdn)

period: int, nbdevup/dn: double

close

3 values

period-1

tk_sar_new(accel, max)

accel: double, max: double

OHLCV

single

1

tk_sarext_new(...)

8 parameters

OHLCV

single

1

tk_mavp_new(min, max, type)

min/max: int, type: tk_ma_type

close + period

single

max-1

tk_midpoint_new(period)

period: int

close

single

period-1

tk_midprice_new(period)

period: int

OHLCV

single

period-1

tk_avgprice_new()

-

OHLCV

single

0

tk_medprice_new()

-

OHLCV

single

0

tk_typprice_new()

-

OHLCV

single

0

tk_wclprice_new()

-

OHLCV

single

0

Momentum Indicators

Function

Parameters

Input

Output

Lookback

tk_rsi_new(period)

period: int

close

single

period

tk_macd_new(fast, slow, signal)

fast, slow, signal: int

close

3 values

slow-1+signal-1

tk_macdext_new(...)

6 parameters

close

3 values

varies

tk_macdfix_new(signal)

signal: int

close

3 values

25+signal-1

tk_stoch_new(k, k_slow, d)

k, k_slow, d: int

OHLCV

2 values

k-1+k_slow-1+d-1

tk_stochf_new(k, d)

k, d: int

OHLCV

2 values

k-1+d-1

tk_stochrsi_new(rsi, stoch, k_smooth, d)

4 int params

close

2 values

varies

tk_adx_new(period)

period: int

OHLCV

3 values

2*period-1

tk_adxr_new(period)

period: int

OHLCV

single

2*period-1

tk_cci_new(period)

period: int

OHLCV

single

period-1

tk_willr_new(period)

period: int

OHLCV

single

period-1

tk_mfi_new(period)

period: int

OHLCV

single

period

tk_mom_new(period)

period: int

close

single

period

tk_roc_new(period)

period: int

close

single

period

tk_rocp_new(period)

period: int

close

single

period

tk_rocr_new(period)

period: int

close

single

period

tk_rocr100_new(period)

period: int

close

single

period

tk_apo_new(fast, slow)

fast, slow: int

close

single

slow-1

tk_ppo_new(fast, slow)

fast, slow: int

close

single

slow-1

tk_cmo_new(period)

period: int

close

single

period

tk_trix_new(period)

period: int

close

single

3*(period-1)

tk_ultosc_new(p1, p2, p3)

p1, p2, p3: int

OHLCV

single

varies

tk_aroon_new(period)

period: int

OHLCV

2 values

period

tk_aroonosc_new(period)

period: int

OHLCV

single

period

tk_dx_new(period)

period: int

OHLCV

single

2*period-1

tk_plus_di_new(period)

period: int

OHLCV

single

2*period-1

tk_minus_di_new(period)

period: int

OHLCV

single

2*period-1

tk_plus_dm_new(period)

period: int

OHLCV

single

period

tk_minus_dm_new(period)

period: int

OHLCV

single

period

tk_bop_new()

-

OHLCV

single

0

Volatility Indicators

Function

Parameters

Input

Output

Lookback

tk_atr_new(period)

period: int

OHLCV

single

period

tk_natr_new(period)

period: int

OHLCV

single

period

tk_trange_new()

-

OHLCV

single

1

tk_stddev_new(period, nbdev)

period: int, nbdev: double

close

single

period-1

tk_var_new(period)

period: int

close

single

period-1

Volume Indicators

Function

Parameters

Input

Output

Lookback

tk_obv_new()

-

OHLCV

single

0

tk_ad_new()

-

OHLCV

single

0

tk_adosc_new(fast, slow)

fast, slow: int

OHLCV

single

slow-1

Statistics Functions

Function

Parameters

Input

Output

Lookback

tk_var_new(period)

period: int

close

single

period-1

tk_stddev_new(period, nbdev)

period: int, nbdev: double

close

single

period-1

tk_linearreg_new(period)

period: int

close

single

period-1

tk_linearreg_slope_new(period)

period: int

close

single

period-1

tk_linearreg_intercept_new(period)

period: int

close

single

period-1

tk_linearreg_angle_new(period)

period: int

close

single

period-1

tk_tsf_new(period)

period: int

close

single

period-1

tk_beta_new(period)

period: int

close + close

single

period-1

tk_correl_new(period)

period: int

close + close

single

period-1

tk_min_new(period)

period: int

close

single

period-1

tk_max_new(period)

period: int

close

single

period-1

tk_sum_new(period)

period: int

close

single

period-1

tk_minmax_new(period)

period: int

close

2 values

period-1

Hilbert Transform (Cycle Indicators)

Function

Parameters

Input

Output

Lookback

tk_ht_dcperiod_new()

-

close

single

63

tk_ht_dcphase_new()

-

close

single

63

tk_ht_trendmode_new()

-

close

single

63

tk_ht_trendline_new()

-

close

single

63

tk_ht_phasor_new()

-

close

2 values

63

tk_ht_sine_new()

-

close

2 values

63

Risk Metrics

Function

Parameters

Input

Output

Lookback

tk_sharpe_new(period, rfr, ann)

period: int, rfr: double, ann: int

returns

single

period-1

tk_sortino_new(period, rfr, target, ann)

4 params

returns

single

period-1

tk_max_drawdown_new()

-

price

single

0

tk_drawdown_new()

-

price

multi

0

tk_calmar_new(period, ann)

period: int, ann: int

returns

single

period-1

tk_hist_var_new(period, conf)

period: int, conf: double

returns

single

period-1

tk_cvar_new(period, conf)

period: int, conf: double

returns

single

period-1

Volatility Models

Function

Parameters

Input

Output

Lookback

tk_ewma_vol_new(lambda, ann)

lambda: double, ann: int

returns

single

0

tk_realized_vol_new(period, ann)

period: int, ann: int

returns

single

period-1

tk_parkinson_vol_new(period, ann)

period: int, ann: int

OHLCV

single

period-1

tk_garch_vol_new(omega, alpha, beta, ann)

4 params

returns

single

0

Structure Analysis

Function

Parameters

Input

Output

Lookback

tk_zigzag_new(dev_pct, depth)

dev_pct: double, depth: int

OHLCV

multi

depth

tk_swing_new(left, right)

left: int, right: int

OHLCV

multi

left+right

tk_pivot_new(type)

type: tk_pivot_type

OHLCV

multi

1

Pattern Recognition

Function

Parameters

Input

Output

Lookback

tk_harmonic_new(dev_pct, tol, max_bars)

3 params

OHLCV

multi

varies

tk_chart_pattern_new(min_bars, max_bars, tol)

3 params

OHLCV

multi

varies

tk_cdl_*_new()

-

OHLCV

single

0-4

Note: There are 61 candlestick pattern functions (tk_cdl_doji_new, tk_cdl_hammer_new, etc.). All follow the same pattern and require OHLCV input.

Destroying Indicators

void tk_free(tk_indicator ind);

Important: Always call tk_free() when done with an indicator to prevent memory leaks.

tk_indicator sma = tk_sma_new(20);
// ... use indicator ...
tk_free(sma);  // Required!

Resetting State

void tk_reset(tk_indicator ind);

Clears all internal state. The indicator returns to initial warmup state.

Update Functions

Single Value Update

tk_result tk_update(tk_indicator ind, double value);

Use for indicators that only need close price:

  • SMA, EMA, WMA, DEMA, TEMA, KAMA, TRIMA, T3

  • RSI, MOM, ROC, ROCP, ROCR, ROCR100

  • APO, PPO, CMO, TRIX

  • STDDEV, VAR, LINEARREG*

  • HT_* indicators

  • Risk metrics (Sharpe, Sortino, etc.)

  • Volatility models (EWMA, Realized, GARCH)

Example:

tk_indicator rsi = tk_rsi_new(14);
for (int i = 0; i < n; i++) {
    tk_result r = tk_update(rsi, close[i]);
    if (r.valid) {
        printf("RSI[%d]: %.2f\n", i, r.value);
    }
}
tk_free(rsi);

OHLCV Update

tk_result tk_update_ohlcv(tk_indicator ind, const tk_ohlcv* bar);

Use for indicators requiring full OHLCV data:

  • ATR, NATR, TRANGE

  • ADX, ADXR, DX, PLUS_DI, MINUS_DI, PLUS_DM, MINUS_DM

  • CCI, WILLR, MFI

  • STOCH, STOCHF

  • OBV, AD, ADOSC

  • SAR, SAREXT

  • AROON, ULTOSC

  • AVGPRICE, MEDPRICE, TYPPRICE, WCLPRICE, BOP, MIDPRICE

  • PARKINSON_VOL

  • ZIGZAG, SWING, PIVOT

  • HARMONIC, CHART_PATTERN

  • All CDL* pattern recognition functions

Example:

tk_indicator atr = tk_atr_new(14);
for (int i = 0; i < n; i++) {
    tk_ohlcv bar = {open[i], high[i], low[i], close[i], volume[i]};
    tk_result r = tk_update_ohlcv(atr, &bar);
    if (r.valid) {
        printf("ATR[%d]: %.4f\n", i, r.value);
    }
}
tk_free(atr);

Multi-Output Updates

MACD

tk_macd_result tk_macd_update(tk_indicator ind, double value);
tk_macd_result tk_macdext_update(tk_indicator ind, double value);
tk_macd_result tk_macdfix_update(tk_indicator ind, double value);

Example:

tk_indicator macd = tk_macd_new(12, 26, 9);
for (int i = 0; i < n; i++) {
    tk_macd_result r = tk_macd_update(macd, close[i]);
    if (r.valid) {
        printf("MACD: %.4f, Signal: %.4f, Hist: %.4f\n", 
               r.macd, r.signal, r.histogram);
    }
}
tk_free(macd);

Bollinger Bands

tk_bbands_result tk_bbands_update(tk_indicator ind, double value);

Stochastic

tk_stoch_result tk_stoch_update(tk_indicator ind, const tk_ohlcv* bar);
tk_stochf_result tk_stochf_update(tk_indicator ind, const tk_ohlcv* bar);
tk_stochrsi_result tk_stochrsi_update(tk_indicator ind, double value);

ADX

tk_adx_result tk_adx_update(tk_indicator ind, const tk_ohlcv* bar);

Aroon

tk_aroon_result tk_aroon_update(tk_indicator ind, const tk_ohlcv* bar);

MINMAX

tk_minmax_result tk_minmax_update(tk_indicator ind, double value);

Hilbert Transform

tk_ht_phasor_result tk_ht_phasor_update(tk_indicator ind, double value);
tk_ht_sine_result tk_ht_sine_update(tk_indicator ind, double value);

Drawdown

tk_drawdown_result tk_drawdown_update(tk_indicator ind, double price);

ZigZag

tk_zigzag_result tk_zigzag_update(tk_indicator ind, const tk_ohlcv* bar);

Swing

tk_swing_result tk_swing_update(tk_indicator ind, const tk_ohlcv* bar);

Pivot Points

tk_pivot_result tk_pivot_update(tk_indicator ind, const tk_ohlcv* bar);

Harmonic Patterns

tk_harmonic_result tk_harmonic_update(tk_indicator ind, const tk_ohlcv* bar);

Chart Patterns

tk_chart_pattern_result tk_chart_pattern_update(tk_indicator ind, const tk_ohlcv* bar);

Special Update Functions

MAVP (Variable Period)

tk_result tk_mavp_update(tk_indicator ind, double value, double period);

Beta

tk_result tk_beta_update(tk_indicator ind, double value0, double value1);

Correlation

tk_result tk_correl_update(tk_indicator ind, double value0, double value1);

Query Functions

Check Ready State

int tk_is_ready(tk_indicator ind);

Returns 1 if indicator has enough data to produce valid output, 0 otherwise.

Get Lookback Period

int tk_lookback(tk_indicator ind);

Returns the number of bars required before first valid output.

Lookback Reference Table:

Indicator

Lookback Formula

SMA(n)

n - 1

EMA(n)

n - 1

RSI(n)

n

MACD(f,s,g)

s - 1 + g - 1

ADX(n)

2n - 1

BBANDS(n)

n - 1

ATR(n)

n

STOCH(k,s,d)

k - 1 + s - 1 + d - 1

HT_*

63

Price transforms

0

Get Indicator Name

const char* tk_name(tk_indicator ind);

Returns the indicator name as a string (e.g., “SMA”, “RSI”, “MACD”).

State Serialization

size_t tk_state_size(tk_indicator ind);
int tk_state_save(tk_indicator ind, void* buffer, size_t buffer_size);
int tk_state_load(tk_indicator ind, const void* buffer, size_t buffer_size);

Save and restore indicator state for persistence or checkpointing.

Version Information

const char* tk_version_string(void);  // "1.2.1"
int tk_version_major(void);           // 1
int tk_version_minor(void);           // 2
int tk_version_patch(void);           // 1

Batch Calculation

Single Value Array

int tk_calculate(
    tk_indicator ind,
    const double* data,
    size_t data_len,
    tk_result* out,
    size_t out_capacity
);

Calculates indicator values for an entire array. Returns number of results written, or negative error code.

Example:

double prices[100] = { /* ... */ };
tk_result results[100];
tk_indicator sma = tk_sma_new(20);

int count = tk_calculate(sma, prices, 100, results, 100);
for (int i = 0; i < count; i++) {
    if (results[i].valid) {
        printf("SMA[%d]: %.2f\n", i, results[i].value);
    }
}
tk_free(sma);

OHLCV Array

int tk_calculate_ohlcv(
    tk_indicator ind,
    const tk_ohlcv* bars,
    size_t bars_len,
    tk_result* out,
    size_t out_capacity
);

Pattern Recognition Batch Functions

Harmonic Pattern Scan

int tk_harmonic_scan(
    const tk_ohlcv* bars,
    int len,
    double deviation_pct,
    double tolerance,
    tk_harmonic_result* out,
    int max_results
);

Scans historical data for harmonic patterns. Returns number of patterns found.

Chart Pattern Scan

int tk_chart_pattern_scan(
    const tk_ohlcv* bars,
    int len,
    tk_chart_pattern_type pattern_type,
    double tolerance,
    tk_chart_pattern_result* out,
    int max_results
);

Scans historical data for chart patterns. Set pattern_type to 0 to scan for all patterns.

Pattern Name Helpers

const char* tk_harmonic_pattern_name(tk_harmonic_type type);
const char* tk_chart_pattern_name(tk_chart_pattern_type type);
double tk_chart_pattern_target(const tk_chart_pattern_result* pattern);

Thread Safety

TechKit is thread-safe by design:

  • No global state: Each indicator instance is completely independent

  • No locks needed: Different threads can use different indicator instances simultaneously

  • Safe pattern:

// Thread 1                    // Thread 2
tk_indicator sma1 = tk_sma_new(20);    tk_indicator sma2 = tk_sma_new(20);
tk_update(sma1, price1);               tk_update(sma2, price2);  // Safe!
tk_free(sma1);                         tk_free(sma2);
  • Unsafe pattern (don’t do this):

// Sharing same indicator across threads - NOT SAFE
tk_indicator shared_sma = tk_sma_new(20);
// Thread 1: tk_update(shared_sma, price1);  // Race condition!
// Thread 2: tk_update(shared_sma, price2);  // Race condition!

Error Handling

Most functions do not return error codes. Instead:

  • Factory functions return NULL on invalid parameters

  • Update functions return {0.0, 0} during warmup period

  • Check result.valid before using result.value

tk_indicator ind = tk_sma_new(-1);  // Invalid period
if (ind == NULL) {
    // Handle error
}

tk_indicator sma = tk_sma_new(20);
tk_result r = tk_update(sma, price);
if (!r.valid) {
    // Still in warmup period, ignore result
}

Memory Management

  • Allocation: tk_xxx_new() allocates memory internally

  • Deallocation: tk_free() must be called to release memory

  • Memory footprint: O(period) for windowed indicators, O(1) for recursive indicators

Indicator Type

Memory

Example

SMA, WMA, TRIMA

O(period)

Ring buffer

EMA, RSI, MACD

O(1)

Fixed state

BBANDS

O(period)

Ring buffer + variance

STOCH

O(period)

High/low tracking

ADX

O(1)

Smoothed values

Complete Example

#include <techkit/techkit_c.h>
#include <stdio.h>

int main() {
    // Sample OHLCV data
    double open[]   = {100.0, 101.0, 102.0, 101.5, 103.0};
    double high[]   = {101.5, 102.5, 103.0, 103.5, 104.0};
    double low[]    = {99.5, 100.5, 101.0, 101.0, 102.0};
    double close[]  = {101.0, 102.0, 101.5, 103.0, 103.5};
    double volume[] = {1000, 1100, 900, 1200, 1150};
    int n = 5;
    
    // Create indicators
    tk_indicator sma = tk_sma_new(3);
    tk_indicator rsi = tk_rsi_new(3);
    tk_indicator atr = tk_atr_new(3);
    tk_indicator macd = tk_macd_new(2, 3, 2);
    
    printf("Version: %s\n\n", tk_version_string());
    
    for (int i = 0; i < n; i++) {
        // Single value indicators
        tk_result sma_r = tk_update(sma, close[i]);
        tk_result rsi_r = tk_update(rsi, close[i]);
        
        // OHLCV indicator
        tk_ohlcv bar = {open[i], high[i], low[i], close[i], volume[i]};
        tk_result atr_r = tk_update_ohlcv(atr, &bar);
        
        // Multi-output indicator
        tk_macd_result macd_r = tk_macd_update(macd, close[i]);
        
        printf("Bar %d: Close=%.2f\n", i, close[i]);
        if (sma_r.valid) printf("  SMA: %.4f\n", sma_r.value);
        if (rsi_r.valid) printf("  RSI: %.2f\n", rsi_r.value);
        if (atr_r.valid) printf("  ATR: %.4f\n", atr_r.value);
        if (macd_r.valid) printf("  MACD: %.4f, Signal: %.4f\n", 
                                  macd_r.macd, macd_r.signal);
        printf("\n");
    }
    
    // Cleanup
    tk_free(sma);
    tk_free(rsi);
    tk_free(atr);
    tk_free(macd);
    
    return 0;
}