Vector#

For more information, please visit Vector.

Guide to Vector (Algorithmic Trading Platform)#

This guide will walk you through the steps of using the Vector platform to create, code, and run your own trading algorithm (algo). The guide covers:

  1. Logging into Vector

  2. Connecting to Telegram

  3. Creating a Strategy

  4. Implementing Your Strategy in main.py

  5. Code Structure Requirements

  6. Basic Price Data, Signals, and Trade Types

  7. Example Strategy Implementation

  8. Paper Testing Your Algorithm

  9. Understanding Classes in Python

  10. Running Your Algo in Live Environment

Logging into Vector#

  1. Navigate to the Vector website/platform.

  2. Click on the Login button. If you are a new user, sign up accordingly.

  3. Enter your email address and password.

  4. Click Log in to access your Vector dashboard.

Connecting to Telegram#

  1. Follow the on-screen instructions to connect your Telegram account.

  2. You may be prompted to open a chat with a Telegram bot.

  3. Copy the confirmation code provided.

  4. Return to Vector and paste the token/code to confirm the connection.

  5. Once connected, your trading updates or alerts will be sent directly to your Telegram account.

Creating a Strategy#

  1. In the Vector dashboard, locate and click on the Create Strategy button.

  2. Enter a name for your strategy (e.g., MyFirstAlgo).

  3. Click Create (or Save) to set up your strategy structure.

  4. You will now have a workspace with a main.py file to start coding your strategy.

Implementing Your Strategy in main.py#

When you create a new strategy, all of your logic must be written inside the main.py file.

Code Organization:

  1. Import necessary libraries and packages.

  2. Define your classes and functions (e.g., Strategy class).

  3. Implement your trading logic within main.py.

  4. Add all dependencies to requirements.txt.

Code Structure Requirements#

Required: trade_type Column#

Your strategy must output a trade_type column in the resulting DataFrame. Valid trade types are:

  • LONG

  • SHORT

  • CLOSE

  • REVERSE_LONG

  • REVERSE_SHORT

  • HOLD

No Redundant Trade Signals#

Repetitive signals like LONG LONG LONG are invalid. You must switch to SHORT, REVERSE_SHORT, CLOSE, or HOLD instead. Similarly, SHORT SHORT SHORT is invalid.

Valid Trade Transitions#

  • If you are currently LONG, valid next transitions are: - SHORT - REVERSE_SHORT - CLOSE - HOLD (temporarily)

  • If you are currently SHORT, valid next transitions are: - LONG - REVERSE_LONG - CLOSE - HOLD (temporarily)

Additional Columns (Optional)#

  • TP (Take Profit): Price level where trade exits profitably.

  • SL (Stop Loss): Price level where trade exits at a loss.

  • TSL (Trailing Stop Loss): A dynamic stop-loss that moves with price.

Basic Price Data, Signals, and Trade Types#

Basic Price Data#

Each row in your dataset must contain the following columns:

  • open: Opening price of the asset.

  • high: Highest price during the period.

  • low: Lowest price during the period.

  • close: Closing price of the asset.

  • volume: Trading volume during the period.

Signals#

The signals column represents trade actions. Valid values include:

  • 1Long Signal (Enter a long position)

  • -1Short Signal (Enter a short position)

  • 1, -1Close (Exit the current position)

  • 2Reverse Short (Open a new position in the opposite direction)

  • -2Reverse Long (Open a new position in the opposite direction)

  • 0No action (Hold)

Pre-installed Packages Available#

Data Processing:
  • numpy (1.26.4)

  • pandas

  • pyarrow

  • scipy

  • statsmodels

Technical Analysis:
  • talib

  • pandas_ta

Machine Learning:
  • scikit-learn

  • tensorflow

  • xgboost

  • lightgbm

Financial:
  • yfinance

  • ccxt

  • alpha_vantage

  • quantstats

  • zipline-reloaded

Utilities:
  • httpx

  • requests

  • websockets

  • joblib

  • tqdm

Example Strategy Implementation in main.py#

import pandas as pd
from enum import Enum

class TradeType(Enum):
    LONG = "LONG"
    SHORT = "SHORT"
    REVERSE_LONG = "REVERSE_LONG"
    REVERSE_SHORT = "REVERSE_SHORT"
    CLOSE = "CLOSE"
    HOLD = "HOLD"

class Strategy:
    def run(self, data: pd.DataFrame) -> pd.DataFrame:
        """
        Execute the strategy on the provided data.

        Args:
            data (pd.DataFrame): Input DataFrame with OHLCV data.

                Expected columns and their data types:
                - datetime: datetime64[ns]
                - open: float64
                - high: float64
                - low: float64
                - close: float64
                - volume: float64

        Returns:
            pd.DataFrame: DataFrame with added indicators and trade types.

            Required columns:
                - trade_type: str (LONG, SHORT, CLOSE, REVERSE_LONG, REVERSE_SHORT, HOLD)

            Optional columns:
                - TP: float64 (Take Profit)
                - SL: float64 (Stop Loss)
                - TSL: float64 (Trailing Stop Loss)
        """
        # Implement your strategy logic here
        return data

Migration Guide: Jupyter to Vector#

This document provides a step-by-step guide to migrate a trading strategy from a Jupyter Notebook environment to the Vector framework. The transition ensures better code structure, modularity, and integration with Vector’s trading engine.

Key Differences#

Feature

Jupyter Implementation

Vector Implementation

Strategy Definition

Standalone functions (process_data, strat)

Class-based approach (Strategy)

Trade Type Handling

No explicit trade type handling

Uses Enum (TradeType) for trade classifications

Execution

Defined in a script with functions

Implemented as methods within a class

Migration Steps#

1. Define Trade Types Using Enum#

In Vector, trade types are represented using an Enum for better organization and readability. Replace any implicit handling of trade types with the following:

Jupyter Implementation (No Explicit Trade Type Enum)

# No trade type definitions

Vector Implementation (Using Enum)

from enum import Enum

class TradeType(Enum):
    LONG = "LONG"
    SHORT = "SHORT"
    REVERSE_LONG = "REVERSE_LONG"
    REVERSE_SHORT = "REVERSE_SHORT"
    CLOSE = "CLOSE"
    HOLD = "HOLD"

2. Convert Functions into a Class#

Instead of standalone functions like process_data and strat, encapsulate them within a class in Vector.

Jupyter Implementation (Function-Based)

def process_data(data):
    return data

def strat(data):
    return data

Vector Implementation (Class-Based Approach)

import pandas as pd

class Strategy:
    def run(self, data: pd.DataFrame) -> pd.DataFrame:
        data = self.process_data(data)
        data = self.strat(data)
        return data

    def process_data(self, data):
        data['trade_type'] = TradeType.HOLD.value
        return data

    def strat(self, data):
        return data

3. Updating the Execution Flow#

In Jupyter, the script executes functions directly. In Vector, instantiate the Strategy class and call its run() method.

Jupyter Execution

# Process Data
processed_data = process_data(data)

# Run Strategy
final_data = strat(processed_data)

Vector Execution

# Instantiate and Run Strategy
strategy = Strategy()
final_data = strategy.run(data)

4. Managing Dependencies#

Ensure that all required modules for the backtest are included in requirements.txt for installation consistency.

Jupyter Requirements

pandas
untrade

Vector Requirements

pandas
enum34

Running Your Algo in Live Environment#

Paper Testing Your Algorithm#

Paper testing (or paper trading) allows you to simulate trades in real-time market conditions without risking actual funds. On the Vector platform, you can:

  1. Switch your strategy to use a paper trading account.

  2. Verify your signals and positions in the paper trading environment.

  3. Analyze results, check performance metrics, and adjust your strategy as needed.

  4. Once satisfied, move on to a live environment.

Once you have successfully tested your algorithm (backtest), you can proceed to live trading.

How We Execute Live Trades#

  • The Vector Paper Trading system mirrors real market scenarios.

  • We use a lookback period of 1,000 candles to calculate indicator values.

  • If your strategy requires more than 1,000 lookback candles, please let us know.

  • After fetching these candles, we pass them to your algo to determine the latest signal.

  • The system then executes an order based on the signal at the closing price of the same timestamp.

Example Trade Execution#

Suppose you are working on a 1-hour timeframe and receive a signal at 2024-01-01 1:30 PM. The signal will be executed at 2024-01-01 2:30 PM, which is the closing time of the 1:30 PM candle. This ensures that trades are placed based on confirmed price data.

Merging Multiple Timeframes#

When working with multiple timeframes in your strategy, it’s crucial to understand how to properly merge and analyze them.

Signal Generation on Larger Timeframes#

The primary rule is that signal generation must be done on the larger timeframe. This ensures more reliable and strategic trading decisions.

Decision-Making Process#

  1. Strategic Priority: Base primary decisions on the larger timeframe analysis, which provides a broader market perspective.

  2. Timeframe Synchronization: Consider that smaller timeframe data may be available while larger timeframe candles are still in progress.

Example Scenario#

Consider a strategy using 15-minute and 4-hour timeframes:

  • At 12:15 PM, the 15-minute candle closes

  • The 4-hour candle (12:00 PM - 4:00 PM) is still in progress

  • Decisions should be based on the last completed 4-hour candle (8:00 AM - 12:00 PM)

Best Practices#

  1. Wait for Completion: Avoid decisions based on incomplete larger timeframe periods

  2. Historical Reference: Use the most recent completed larger timeframe period for decision-making

  3. Data Consistency: Ensure your testing environment properly handles different timeframe closures

Implementation Considerations#

  • Live trading requires careful handling of ongoing vs. completed periods

  • Backtesting benefits from complete historical data

  • Synchronize decisions with larger timeframe period closures

Understanding Correlation Between Symbols#

Correlation analysis helps traders understand how different trading pairs move in relation to each other. This knowledge is valuable for diversification, pair trading strategies, and risk management.

What is Correlation?#

Correlation measures the relationship between two assets: - A correlation of +1 means the assets move perfectly together - A correlation of -1 means they move in opposite directions - A correlation of 0 means there is no linear relationship

Types of Correlation Analysis#

  1. Static Correlation - Measures relationship over a fixed period - Provides a broad overview of asset relationships - Useful for long-term portfolio planning

  2. Rolling Correlation - Calculates correlation over moving time windows - Shows how relationships change over time - More useful for active trading strategies

  3. Dynamic Correlation - Updates in real-time as new data arrives - Helps identify changing market conditions - Important for risk management

Using Correlation in Trading#

  1. Pair Trading Opportunities - Look for historically correlated pairs - Trade when correlation temporarily breaks down - Exit when relationship returns to normal

  2. Portfolio Management - Choose assets with low correlation to diversify - Reduce overall portfolio risk - Improve risk-adjusted returns

  3. Market Analysis - Compare assets to market benchmarks - Identify market trends and regimes - Spot potential market shifts

Important Considerations#

  1. Time Horizon - Short-term correlations can be unstable - Medium-term (20-60 days) commonly used - Long-term for strategic decisions

  2. Market Conditions - Correlations often change during market stress - May break down during high volatility - Different behavior in bull vs bear markets

  3. Trading Implications - Don’t rely solely on correlation - Consider fundamental factors - Monitor correlation stability

Warning Signs#

Be cautious when: - Correlations suddenly change - Relationships become unstable - Market conditions are extremely volatile - Trading volumes are low

Remember that past correlations don’t guarantee future relationships, and always combine correlation analysis with other trading indicators and research.

Errors#

The following errors may occur during execution. Each error highlights a potential issue in the strategy, configuration, or data integrity.

  • Frontlook bias detected This error occurs when future data is accessed before its corresponding datetime in the dataset, leading to misleading results.

    Message: Frontlook bias detected at {datetime} with differences: {datetime}

    Reference: See Frontlook Bias Test in the Strategy Submission section.

  • Failed to install requirements: Some required dependencies failed to install. Ensure all necessary packages are correctly listed and installed.

  • Missing columns in result DataFrame: The expected columns are missing from the results. This typically happens when the strategy does not generate all required fields. Message: Columns {’, ‘.join(missing_columns)} are missing in the result DataFrame Required columns:

  • open

  • high

  • low

  • close

  • volume

  • trade_type

  • signals

  • Duplicate trade type detected Consecutive trades of the same type (e.g., multiple long or short entries without exits) suggest a potential issue in the strategy logic.

    Message: Consecutive trade_type detected.

    Reference: See No Redundant Trade Signals in the Vector section.

  • Invalid leverage Leverage must be between 1 and 5. Any value outside this range is not allowed.

    Example: Using leverage of 6 or 0.5 will trigger this error.

    Reference: See How to Backtest Your Strategy in the Strategy Submission section.

  • Invalid position Position size must be between 50 and 100. If the position is too small or too large, it will be rejected.

    Example: A position of 30 or 120 will trigger this error.

    Reference: See How to Backtest Your Strategy in the Strategy Submission section.

  • Liquidation event: The position has been liquidated due to margin requirements or excessive losses. This may indicate improper risk management.

  • Invalid symbol during code save: The symbol used while saving the code is not recognized or does not match supported trading pairs. Message: Invalid symbol during code save: {symbol}

  • Invalid timeframe during code save: The timeframe selected is invalid or not supported. Ensure the correct format is used. Message: Invalid timeframe during code save: {timeframe}

  • Duplicate pair found: A trading pair with the same timeframe already exists in the system, leading to potential conflicts. Message: Duplicate pair found: {symbol} {timeframe}

  • Strategy class is missing or renamed The Strategy class is required but was not found. It may have been renamed or incorrectly defined.

    Reference: See Vector Template in the Example section.

  • Missing `run` function in Strategy class: The run function is missing from the Strategy class. This function is essential for executing the strategy and processing trades.

By following these steps, you can confidently develop, test, and deploy your trading strategies using the Vector platform.