WU Trading Library 0.2.0
A backtesting and trading strategy library
Loading...
Searching...
No Matches
basic.c File Reference
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include "wu.h"

Go to the source code of this file.

Data Structures

struct  BuyPositionResult
 An auxiliary struct to hold the result of setting a buy position and calculating the total cost. More...

Functions

WU_PortfolioParams wu_portfolio_params_default (void)
 This file implements a basic portfolio management system that supports multiple assets with a shared cash pool.
static double calculate_years_held (WU_TimeStamp open_time, WU_TimeStamp close_time)
 Helper function to calculate the time difference in years between two timestamps, accounting for different time units.
static double execution_price (double price, WU_ExecutionPolicy policy, bool is_buy)
 Calculates the execution price based on the execution policy.
static double calculate_positions_value (WU_PositionVector *vec, double price)
 Helper function to calculate the total value of all positions in a position vector at a given price.
static double calculate_portfolio_value (const struct WU_Portfolio_ *portfolio)
 To calculate the total value of the portfolio, an iterative process is used to sum the value of each position across all assets, based on the last known price for each asset.
static double calculate_position_size (WU_BasicPortfolio portfolio, WU_Signal signal)
 This function calculates the position size for a given signal based on the portfolio's position sizing parameters.
static double compute_total_cost (double quantity, double price, WU_ExecutionPolicy policy)
 Computes the total cost of a trade including transaction costs.
static struct BuyPositionResult set_buy_position (WU_BasicPortfolio portfolio, WU_Signal signal)
 This function calculates the position size for a buy signal, applies execution policy to determine the effective price, and computes the total cost of the purchase including transaction costs.
static double calculate_total_cost_basis (WU_PositionVector *vec)
 This function calculates the total cost basis for all active positions in a given position vector.
static void execute_buy (WU_BasicPortfolio portfolio, WU_Signal signal, int asset_index)
 This function executes a buy signal.
static void close_and_update_portfolio (WU_BasicPortfolio portfolio, double quantity, double cost_basis, double sell_price, WU_CloseReason reason)
 This function handles the logic for closing a position and updating the portfolio's cash balance and trading statistics.
static void execute_sell (WU_BasicPortfolio portfolio, WU_Signal signal, int asset_index)
 This function executes a sell signal.
static bool close_position (WU_BasicPortfolio portfolio, struct WU_Position_ pos, double current_price)
 This function checks if a position should be closed based on the current price and the portfolio's stop-loss and take-profit thresholds.
static void check_and_close_positions (WU_BasicPortfolio portfolio, int asset_index, double current_price)
 This function iterates through all active positions for a given asset and checks if any of them can be closed based on the current price and the portfolio's stop-loss and take-profit thresholds.
static double calculate_portfolio_pnl (const struct WU_Portfolio_ *portfolio)
 The profit and loss (PnL) of the portfolio is calculated by taking the current total value of the portfolio (cash + value of all positions) and subtracting the initial cash invested.
static double calculate_total_short_value (WU_BasicPortfolio p)
 Helper function to calculate total value of all short positions across all assets in the portfolio.
static void update_prices_and_check_exits (WU_BasicPortfolio p, const WU_Signal *signals, int count)
 Helper function to update last prices, apply borrow interest on short positions, check exits, and update stats with current portfolio state.
static void process_sell_signals (WU_BasicPortfolio p, const WU_Signal *signals, int count)
 Helper function to process all sell signals.
static int count_buy_signals (const WU_Signal *signals, int count)
 Helper function to count valid buy signals.
static bool uses_strategy_guided_allocation (WU_BasicPortfolio p, const WU_Signal *signals, int count)
 Helper function to check if signals use strategy-guided allocation.
static void process_buy_signals (WU_BasicPortfolio p, const WU_Signal *signals, int count, int buy_count)
 Helper function to process all buy signals.
static void execute_pending_orders (WU_BasicPortfolio p)
 Helper function to execute pending orders from previous update.
static void update_portfolio (WU_Portfolio portfolio, const WU_Signal *signals)
 The update_portfolio function is the core of the portfolio management logic.
static void wu_basic_portfolio_free (struct WU_Portfolio_ *portfolio)
 This function is responsible for freeing all memory associated with the portfolio.
static WU_PositionVector ** initialize_positions (const char *symbols[], int num_assets)
 Helper function to initialize position vectors for all assets.
WU_BasicPortfolio wu_basic_portfolio_new (WU_PortfolioParams params, const char *symbols[])
 This constructor function creates a new basic portfolio instance.
double wu_basic_portfolio_asset_value (WU_BasicPortfolio portfolio, int asset_index)
 The value of a specific asset's positions is calculated by summing the value of each active position.
double wu_basic_portfolio_asset_quantity (WU_BasicPortfolio portfolio, int asset_index)
 Computes the total quantity held for a specific asset by summing the quantities of all active positions in the corresponding position vector.

Function Documentation

◆ calculate_portfolio_pnl()

double calculate_portfolio_pnl ( const struct WU_Portfolio_ * portfolio)
static

The profit and loss (PnL) of the portfolio is calculated by taking the current total value of the portfolio (cash + value of all positions) and subtracting the initial cash invested.

This provides a measure of the overall performance of the portfolio since inception.

Definition at line 493 of file basic.c.

◆ calculate_portfolio_value()

double calculate_portfolio_value ( const struct WU_Portfolio_ * portfolio)
static

To calculate the total value of the portfolio, an iterative process is used to sum the value of each position across all assets, based on the last known price for each asset.

The cash balance is then added to this total to get the overall portfolio value. This function has a complexity of O(N*M) where N is the number of assets and M is the average number of positions per asset. Although the performance can be an issue, it provides an accurate valuation of the portfolio at a given point in time. In the future, it can consider caching the total value and only recalculating when there are changes to positions or prices, to improve performance. Additionally, it can be optimized by maintaining a running total of the portfolio value that gets updated when positions modified.

Definition at line 130 of file basic.c.

◆ calculate_position_size()

double calculate_position_size ( WU_BasicPortfolio portfolio,
WU_Signal signal )
static

This function calculates the position size for a given signal based on the portfolio's position sizing parameters.

It supports multiple sizing strategies, including absolute size, percentage of cash, equal percentage of portfolio, and strategy-guided sizing. The function takes into account the current price of the asset and the available cash in the portfolio to determine the appropriate quantity to buy or sell. It ensures that the calculated position size does not exceed the available cash for buy signals and can be adjusted based on the signal's quantity for strategy-guided sizing.

Definition at line 152 of file basic.c.

◆ calculate_positions_value()

double calculate_positions_value ( WU_PositionVector * vec,
double price )
static

Helper function to calculate the total value of all positions in a position vector at a given price.

Definition at line 104 of file basic.c.

◆ calculate_total_cost_basis()

double calculate_total_cost_basis ( WU_PositionVector * vec)
static

This function calculates the total cost basis for all active positions in a given position vector.

It iterates through each position, checks if it is active, and if so, it multiplies the quantity by the price to get the cost for that position, and sums it up to get the total cost basis. This total cost basis is used when closing positions to determine the profit and loss (PnL) from the trade, as it represents the total amount invested in those positions.

Definition at line 267 of file basic.c.

◆ calculate_total_short_value()

double calculate_total_short_value ( WU_BasicPortfolio p)
static

Helper function to calculate total value of all short positions across all assets in the portfolio.

Definition at line 503 of file basic.c.

◆ calculate_years_held()

double calculate_years_held ( WU_TimeStamp open_time,
WU_TimeStamp close_time )
static

Helper function to calculate the time difference in years between two timestamps, accounting for different time units.

Definition at line 48 of file basic.c.

◆ check_and_close_positions()

void check_and_close_positions ( WU_BasicPortfolio portfolio,
int asset_index,
double current_price )
static

This function iterates through all active positions for a given asset and checks if any of them can be closed based on the current price and the portfolio's stop-loss and take-profit thresholds.

If a position is closed, then it is removed from the position vector.

Definition at line 473 of file basic.c.

◆ close_and_update_portfolio()

void close_and_update_portfolio ( WU_BasicPortfolio portfolio,
double quantity,
double cost_basis,
double sell_price,
WU_CloseReason reason )
static

This function handles the logic for closing a position and updating the portfolio's cash balance and trading statistics.

It calculates the proceeds from the sale, the transaction cost based on the defined transaction cost policy, and the profit and loss (PnL) from the trade. The portfolio's cash balance is updated by adding the proceeds and subtracting the transaction cost, and fees are tracked in stats.

Definition at line 332 of file basic.c.

◆ close_position()

bool close_position ( WU_BasicPortfolio portfolio,
struct WU_Position_ pos,
double current_price )
static

This function checks if a position should be closed based on the current price and the portfolio's stop-loss and take-profit thresholds.

For short positions (negative quantity), the PnL logic is inverted. NAN values disable stop-loss or take-profit.

Definition at line 435 of file basic.c.

◆ compute_total_cost()

double compute_total_cost ( double quantity,
double price,
WU_ExecutionPolicy policy )
static

Computes the total cost of a trade including transaction costs.

Supports both fixed and proportional transaction cost models.

Definition at line 206 of file basic.c.

◆ count_buy_signals()

int count_buy_signals ( const WU_Signal * signals,
int count )
static

Helper function to count valid buy signals.

Definition at line 586 of file basic.c.

◆ execute_buy()

void execute_buy ( WU_BasicPortfolio portfolio,
WU_Signal signal,
int asset_index )
static

This function executes a buy signal.

For portfolios without positions or with long positions, it creates new long positions. When there are short positions (negative quantity), it closes them (buy to cover). It updates the portfolio's cash balance and tracks transaction fees in stats.

Definition at line 285 of file basic.c.

◆ execute_pending_orders()

void execute_pending_orders ( WU_BasicPortfolio p)
static

Helper function to execute pending orders from previous update.

This is used for NEXT_CLOSE execution policy.

Definition at line 653 of file basic.c.

◆ execute_sell()

void execute_sell ( WU_BasicPortfolio portfolio,
WU_Signal signal,
int asset_index )
static

This function executes a sell signal.

For long positions, it closes existing positions. For short and both-direction portfolios, it can initiate a short sale even without existing positions (borrowing assets).

Definition at line 353 of file basic.c.

◆ execution_price()

double execution_price ( double price,
WU_ExecutionPolicy policy,
bool is_buy )
inlinestatic

Calculates the execution price based on the execution policy.

For IMMEDIATE and NEXT_CLOSE, returns the base price. For FIXED_SLIPPAGE, applies a fixed slippage percentage. For RANDOM_SLIPPAGE, applies random slippage based on mean and stdev.

Definition at line 79 of file basic.c.

◆ initialize_positions()

WU_PositionVector ** initialize_positions ( const char * symbols[],
int num_assets )
static

Helper function to initialize position vectors for all assets.

Allocates memory and creates position vectors. Returns NULL on failure.

Definition at line 735 of file basic.c.

◆ process_buy_signals()

void process_buy_signals ( WU_BasicPortfolio p,
const WU_Signal * signals,
int count,
int buy_count )
static

Helper function to process all buy signals.

If cash splitting is enabled, it divides the available cash equally among the buy signals to ensure that the total allocated cash does not exceed the portfolio's cash balance. Each buy signal is processed sequentially, and the cash balance is updated after each purchase to reflect the remaining cash for subsequent buys. If cash splitting is not enabled, each buy signal is processed with the full available cash, which may lead to some buy signals being ignored if the cash runs out. This function ensures that the portfolio's cash management is consistent with the defined position sizing strategy and prevents over-allocation of funds when multiple buy signals are present.

Definition at line 628 of file basic.c.

◆ process_sell_signals()

void process_sell_signals ( WU_BasicPortfolio p,
const WU_Signal * signals,
int count )
static

Helper function to process all sell signals.

It iterates through the signals, validates them, and if a signal is a sell signal, it calls the execute_sell function to close the corresponding positions. This function should be called first to ensure that all sell signals are handled before processing buy signals, which is important for proper cash management and to avoid situations where buy signals are ignored due to insufficient cash after processing sell signals.

Definition at line 574 of file basic.c.

◆ set_buy_position()

struct BuyPositionResult set_buy_position ( WU_BasicPortfolio portfolio,
WU_Signal signal )
static

This function calculates the position size for a buy signal, applies execution policy to determine the effective price, and computes the total cost of the purchase including transaction costs.

It also checks if the total cost exceeds the available cash in the portfolio, and if so, it adjusts the quantity to fit within the cash constraints. The result includes the position details (timestamp, quantity, price) and the total cost and transaction cost for the trade.

Definition at line 227 of file basic.c.

◆ update_portfolio()

void update_portfolio ( WU_Portfolio portfolio,
const WU_Signal * signals )
static

The update_portfolio function is the core of the portfolio management logic.

It processes incoming signals to update the portfolio's state. For IMMEDIATE execution, signals are processed right away. For NEXT_CLOSE execution, signals are stored and executed on the next update. The function first executes any pending orders from previous update, then updates prices and checks for exits, processes sell signals, and finally processes buy signals (or stores them as pending).

Definition at line 680 of file basic.c.

◆ update_prices_and_check_exits()

void update_prices_and_check_exits ( WU_BasicPortfolio p,
const WU_Signal * signals,
int count )
static

Helper function to update last prices, apply borrow interest on short positions, check exits, and update stats with current portfolio state.

Definition at line 518 of file basic.c.

◆ uses_strategy_guided_allocation()

bool uses_strategy_guided_allocation ( WU_BasicPortfolio p,
const WU_Signal * signals,
int count )
static

Helper function to check if signals use strategy-guided allocation.

Definition at line 600 of file basic.c.

◆ wu_basic_portfolio_asset_quantity()

double wu_basic_portfolio_asset_quantity ( WU_BasicPortfolio portfolio,
int asset_index )

Computes the total quantity held for a specific asset by summing the quantities of all active positions in the corresponding position vector.

Get total quantity held for a specific asset.

It does bound checking.

Definition at line 827 of file basic.c.

◆ wu_basic_portfolio_asset_value()

double wu_basic_portfolio_asset_value ( WU_BasicPortfolio portfolio,
int asset_index )

The value of a specific asset's positions is calculated by summing the value of each active position.

Get current value of a specific asset's positions.

This function does bound checking.

Definition at line 812 of file basic.c.

◆ wu_basic_portfolio_free()

void wu_basic_portfolio_free ( struct WU_Portfolio_ * portfolio)
static

This function is responsible for freeing all memory associated with the portfolio.

It iterates through each asset's position vector and deletes it, then frees the array of position vectors, pending orders array, deletes the portfolio statistics, and finally frees the portfolio structure itself. This ensures that all resources are properly released when the portfolio is no longer needed, preventing memory leaks.

Definition at line 719 of file basic.c.

◆ wu_basic_portfolio_new()

WU_BasicPortfolio wu_basic_portfolio_new ( WU_PortfolioParams params,
const char * symbols[] )

This constructor function creates a new basic portfolio instance.

Creates a new basic portfolio instance with the specified parameters and asset symbols.

It takes in the portfolio parameters and an array of asset symbols, and initializes the portfolio's internal state accordingly. Memory is dynamically allocated for the portfolio structure and the position vectors for each asset. The function also sets up the function pointers for the portfolio operations (update, value, pnl, delete) and initializes the cash balance and trading statistics. If any memory allocation fails, it ensures that all previously allocated resources are freed to prevent memory leaks.

Definition at line 764 of file basic.c.

◆ wu_portfolio_params_default()

WU_PortfolioParams wu_portfolio_params_default ( void )

This file implements a basic portfolio management system that supports multiple assets with a shared cash pool.

Returns default portfolio parameters with reasonable values.

The portfolio can process buy and sell signals, manage positions for each asset, and calculate the total value and profit/loss (PnL) of the portfolio. It also includes features such as transaction costs, slippage, stop-loss, and take-profit mechanisms. Returns default portfolio parameters with reasonable values.

Definition at line 19 of file basic.c.