i just asked grok who is investing in AI and whether AI will kill retail trading

Discussion in 'Artificial Intelligence' started by mute9003, May 26, 2025 at 11:42 AM.

  1. Dismiss Notice
  1. Sprout

    Sprout

    Congrats on expressing higher Agency

    Additional details:
    https://www.perplexity.ai/search/elaborate-and-identify-what-in-tHQVVZQoQ3a4P4ovdYIksw#1

    It seems like the concepts of jerk and snap are not used much in quant finance except as metaphors for higer order derivatives defined in the options market.

    The concepts are intriguing yet since the promoter discounts time as irrelevant, there is a logical incongruency. This is due to the whole basis of measuring the base of velocity involves a factor of time.
     
    Last edited: May 27, 2025 at 10:34 AM
    HawaiianIceberg likes this.
  2. Sprout

    Sprout

    upload_2025-5-27_8-21-12.png

    The code that was shared is a mean-reversion strategy, it does not implement jerk and snap

    upload_2025-5-27_7-23-51.png

    I extensively use diagrams (artifacts in mermaid, plantUML, YAML, etc) in my coding efforts.
    It causes better outputs and when used as references for inputs, allows for better context management.

    While Sonnet 4's response sounds authoritative and confidence high (as all LLMs), when confronted with errors (that only a domain expert would know), they pivot and return an equally faulty yet confident reply.

    Best to take LLM responses with a grain-of-salt.
     
    Last edited: May 27, 2025 at 11:21 AM
  3. MarkBrown

    MarkBrown

    what is the question about jerk and jounce?

    i use them both in all my trading to identify sudden moves that can not be identified by eye or feel. this puts math to the task of discovering when it's safe to join the the directional move.
     
  4. MarkBrown

    MarkBrown

    Key Modifications:




      • Jerk and snap now directly influence the trading signal
      • Added sensitivity parameters to control their impact
      • Enhanced debugging to show derivative information
      • Maintained the core mean reversion logic
    The strategy now:




      • Calculates price derivatives
      • Uses jerk to amplify signals during significant momentum changes
      • Uses snap to further modify signal sensitivity
      • Provides more detailed logging of derivative information
    Potential Use Cases:




      • Detecting sudden price momentum shifts
      • Adding sensitivity to mean reversion signals
      • Identifying potential trend acceleration

    Code:
    using System;[/B]
    [B]using System.Collections.Generic;
    using System.Linq;
    using PowerLanguage.Function;
    
    namespace PowerLanguage.Strategy
    {
        [IOGMode(IOGMode.Enabled)]
        public class ctest1 : SignalObject
        {
            #region Strategy Parameters
          
            [Input]
            public int LookbackWindow { get; set; }
          
            [Input]
            public double SignalThreshold { get; set; }
          
            [Input]
            public double JerkSensitivity { get; set; }
          
            [Input]
            public double SnapSensitivity { get; set; }
          
            [Input]
            public bool UseJerkEnhancement { get; set; }
          
            #endregion
          
            #region Private Variables
          
            private List<double> priceHistory;
            private List<double> signalHistory;
            private List<double> velocityHistory;
            private List<double> accelerationHistory;
            private List<double> jerkHistory;
            private List<double> snapHistory;
          
            private double currentCompositeSignal;
            private double previousCompositeSignal;
            private int currentPosition;
          
            #endregion
          
            #region Constructor
          
            public ctest1(object _ctx) : base(_ctx)
            {
                // Default parameters
                LookbackWindow = 10;
                SignalThreshold = 0.005;
                JerkSensitivity = 0.1;
                SnapSensitivity = 0.05;
                UseJerkEnhancement = true;
            }
          
            #endregion
          
            #region Initialization
          
            protected override void Create()
            {
                // Initialize collections
                priceHistory = new List<double>();
                signalHistory = new List<double>();
                velocityHistory = new List<double>();
                accelerationHistory = new List<double>();
                jerkHistory = new List<double>();
                snapHistory = new List<double>();
            }
          
            #endregion
          
            #region Main Strategy Logic
          
            protected override void CalcBar()
            {
                // Update price history
                UpdatePriceHistory();
              
                // Need minimum bars for calculations
                if (priceHistory.Count < 5)
                    return;
                  
                // Calculate velocity derivatives
                CalculateVelocityDerivatives();
              
                // Generate composite signal with jerk and snap enhancement
                currentCompositeSignal = GenerateEnhancedCompositeSignal();
              
                // Generate trading decision
                int tradingSignal = GenerateTradingDecision();
              
                // Output debug information
                OutputDetailedDebugInfo(tradingSignal);
              
                // Maintain history size
                MaintainHistorySize();
            }
          
            #endregion
          
            #region Enhanced Signal Generation
          
            private void CalculateVelocityDerivatives()
            {
                if (priceHistory.Count < 5) return;
              
                var recentPrices = TakeLast(priceHistory, Math.Min(priceHistory.Count, LookbackWindow));
              
                // Velocity (1st derivative)
                var velocity = CalculateGradient(recentPrices);
                if (velocity.Count > 0)
                    velocityHistory.Add(velocity[velocity.Count - 1]);
              
                // Acceleration (2nd derivative)
                if (velocityHistory.Count >= 2)
                {
                    var acceleration = CalculateGradient(TakeLast(velocityHistory, Math.Min(velocityHistory.Count, 50)));
                    if (acceleration.Count > 0)
                        accelerationHistory.Add(acceleration[acceleration.Count - 1]);
                }
              
                // Jerk (3rd derivative)
                if (accelerationHistory.Count >= 2)
                {
                    var jerk = CalculateGradient(TakeLast(accelerationHistory, Math.Min(accelerationHistory.Count, 30)));
                    if (jerk.Count > 0)
                        jerkHistory.Add(jerk[jerk.Count - 1]);
                }
              
                // Snap/Jounce (4th derivative)
                if (jerkHistory.Count >= 2)
                {
                    var snap = CalculateGradient(TakeLast(jerkHistory, Math.Min(jerkHistory.Count, 20)));
                    if (snap.Count > 0)
                        snapHistory.Add(snap[snap.Count - 1]);
                }
            }
          
            private double GenerateEnhancedCompositeSignal()
            {
                var recentPrices = TakeLast(priceHistory, Math.Min(priceHistory.Count, LookbackWindow));
              
                if (recentPrices.Count < 5) return 0;
              
                // Basic mean reversion signal
                double currentPrice = recentPrices[recentPrices.Count - 1];
                double meanPrice = Average(recentPrices);
                double baseSignal = (currentPrice - meanPrice) / meanPrice;
              
                // Jerk and Snap Enhancement
                if (UseJerkEnhancement &&
                    jerkHistory.Count > 0 &&
                    snapHistory.Count > 0)
                {
                    double lastJerk = Math.Abs(jerkHistory[jerkHistory.Count - 1]);
                    double lastSnap = Math.Abs(snapHistory[snapHistory.Count - 1]);
                  
                    // Jerk enhancement logic
                    if (lastJerk > JerkSensitivity)
                    {
                        // Amplify signal when jerk is significant
                        baseSignal *= (1 + lastJerk);
                    }
                  
                    // Snap additional modification
                    if (lastSnap > SnapSensitivity)
                    {
                        // Further modify signal based on snap
                        baseSignal *= (1 + lastSnap);
                    }
                }
              
                return baseSignal;
            }
          
            #endregion
          
            #region Trading Decision
          
            private int GenerateTradingDecision()
            {
                // Basic mean reversion trading logic
                if (currentPosition == 0)
                {
                    // Long entry when signal is negative (price below mean)
                    if (currentCompositeSignal < -SignalThreshold)
                    {
                        Output.WriteLine($"LONG ENTRY: Signal {currentCompositeSignal:F6}");
                        return 1;
                    }
                    // Short entry when signal is positive (price above mean)
                    else if (currentCompositeSignal > SignalThreshold)
                    {
                        Output.WriteLine($"SHORT ENTRY: Signal {currentCompositeSignal:F6}");
                        return -1;
                    }
                }
                else
                {
                    // Exit logic with jerk-enhanced sensitivity
                    double exitThreshold = SignalThreshold * 2;
                  
                    // Long position exit
                    if (currentPosition > 0 &&
                        currentCompositeSignal > exitThreshold)
                    {
                        Output.WriteLine($"EXIT LONG: Signal {currentCompositeSignal:F6}");
                        return -1;
                    }
                  
                    // Short position exit
                    if (currentPosition < 0 &&
                        currentCompositeSignal < -exitThreshold)
                    {
                        Output.WriteLine($"EXIT SHORT: Signal {currentCompositeSignal:F6}");
                        return 1;
                    }
                }
              
                return 0; // Hold current position
            }
          
            #endregion
          
            #region Utility Functions
          
            private List<double> CalculateGradient(List<double> data)
            {
                var gradient = new List<double>();
              
                if (data.Count < 2) return gradient;
              
                // Forward difference for first point
                gradient.Add(data[1] - data[0]);
              
                // Central difference for middle points
                for (int i = 1; i < data.Count - 1; i++)
                {
                    gradient.Add((data[i + 1] - data[i - 1]) / 2.0);
                }
              
                // Backward difference for last point
                gradient.Add(data[data.Count - 1] - data[data.Count - 2]);
              
                return gradient;
            }
          
            private double Average(List<double> values)
            {
                return values.Count == 0 ? 0 : values.Average();
            }
          
            private List<double> TakeLast(List<double> source, int count)
            {
                return source.Count <= count
                    ? new List<double>(source)
                    : source.Skip(source.Count - count).ToList();
            }
          
            private void MaintainHistorySize()
            {
                const int maxHistorySize = 100;
              
                if (velocityHistory.Count > maxHistorySize)
                    velocityHistory.RemoveAt(0);
                  
                if (accelerationHistory.Count > maxHistorySize)
                    accelerationHistory.RemoveAt(0);
                  
                if (jerkHistory.Count > maxHistorySize)
                    jerkHistory.RemoveAt(0);
                  
                if (snapHistory.Count > maxHistorySize)
                    snapHistory.RemoveAt(0);
            }
          
            private void OutputDetailedDebugInfo(int tradingSignal)
            {
                // Detailed logging of derivatives and signal
                if (Bars.CurrentBar % 5 == 0)
                {
                    string signalDescription = tradingSignal switch
                    {
                        1 => "LONG ENTRY",
                        -1 => "SHORT ENTRY",
                        0 => "HOLD",
                        _ => "NO ACTION"
                    };
                  
                    // Log derivatives if available
                    string derivativesInfo = jerkHistory.Count > 0 && snapHistory.Count > 0
                        ? $"Jerk: {jerkHistory[jerkHistory.Count - 1]:F6}, " +
                          $"Snap: {snapHistory[snapHistory.Count - 1]:F6}"
                        : "Derivatives not yet calculated";
                  
                    Output.WriteLine(
                        $"Bar {Bars.CurrentBar}: " +
                        $"Signal: {currentCompositeSignal:F6}, " +
                        $"Action: {signalDescription}, " +
                        $"{derivativesInfo}"
                    );
                }
            }
          
            #endregion
        }
    }





    =================
    previous version comments below


    Overview

    This is a sophisticated trading strategy implemented in MultiCharts.NET, specifically designed for mean reversion trading with advanced signal generation and risk management techniques.

    Core Strategy Philosophy
    The strategy aims to:

    1. Identify price deviations from a mean
    2. Generate trading signals based on these deviations
    3. Implement strict risk and position management
    4. Track and analyze trading performance
    Key Components
    1. Input Parameters

    csharp
    [Input]
    public int LookbackWindow { get; set; } // How many bars to analyze
    [Input]
    public double SignalThreshold { get; set; } // Sensitivity of trading signals
    [Input]
    public int PositionSize { get; set; } // Number of contracts/shares to trade
    [Input]
    public double TransactionCost { get; set; } // Cost per trade
    [Input]
    public double RiskFactor { get; set; } // Risk multiplier
    [Input]
    public bool EnableQuantum { get; set; } // Advanced signal generation flag
    [Input]
    public bool EnableBacterial { get; set; } // Alternative signal processing
    [Input]
    public bool EnableFractional { get; set; } // Fractional position sizing
    2. Strategy Initialization
    In the constructor, the strategy sets default, somewhat aggressive parameters:

    • Short lookback window (10 bars)
    • Very sensitive signal threshold (0.005)
    • Minimal position sizing
    • Low transaction costs
    • Maximum holding periods (12 bars max, 3 bars minimum)
    3. Signal Generation Methodology
    The strategy uses a multi-layered signal generation approach:

    Price Derivatives Calculation
    The CalculateVelocityDerivatives() method computes:

    • Velocity (1st derivative of price)
    • Acceleration (2nd derivative)
    • Jerk (3rd derivative)
    • Snap (4th derivative)
    This allows for complex, multi-dimensional price movement analysis.

    Composite Signal Generation
    GenerateCompositeSignal() creates a mean reversion signal:

    • Calculates the mean price over the lookback window
    • Compares current price to mean price
    • Generates a normalized signal:
      • Positive signal → Price above mean (potential short)
      • Negative signal → Price below mean (potential long)
    Example calculation:


    csharp
    double primarySignal = (currentPrice - meanPrice) / meanPrice;
    primarySignal = primarySignal * 10; // Amplify sensitivity
    4. Trading Decision Logic
    GenerateTradingDecision() determines trade actions based on:

    • Current position status
    • Risk-adjusted signal
    • Minimum/maximum holding periods
    Trade scenarios:

    • Forced exit after max holding period
    • Exit on strong signal reversal
    • Long entry when price is below mean
    • Short entry when price is above mean
    5. Trade Execution
    ExecuteTrade() handles:

    • Sending market orders
    • Tracking position duration
    • Logging trade details
    • Updating trade counters
    6. Performance Tracking
    UpdatePerformanceMetrics() monitors:

    • Peak equity
    • Maximum drawdown
    • Trade count
    7. Advanced Utility Functions
    Includes custom implementations of:

    • Standard deviation calculation
    • Mean calculation
    • List manipulation
    • Gradient/derivative calculation
    Unique Features
    Derivative-Based Signal Generation
    Unlike traditional moving average crossover strategies, this approach:

    • Calculates multiple price derivatives
    • Uses non-linear signal generation
    • Adapts to price movement characteristics
    Risk Management
    • Dynamic risk factor
    • Position duration limits
    • Forced exits
    • Adaptive signal thresholds
    Debugging & Transparency
    Extensive logging and debug output:

    • Prints detailed trade reasoning
    • Shows signal components
    • Tracks performance metrics
    Potential Use Cases
    • Mean reversion trading
    • Volatile market environments
    • Stocks with mean-reverting tendencies
    • Algorithmic trading research
    Limitations
    • Assumes transaction costs are minimal
    • Relies heavily on lookback window selection
    • May overfit to specific market conditions
    Would you like me to elaborate on any specific aspect of the strategy? I can dive deeper into signal generation, risk management, or any other component.

    M
    how does it use jerk and jounce


    Great question! Let's dive deep into how this strategy calculates and potentially uses jerk and jounce (snap).

    Derivative Calculation Method

    csharp
    private void CalculateVelocityDerivatives()
    {
    if (priceHistory.Count < 5) return;

    var recentPrices = TakeLast(priceHistory, Math.Min(priceHistory.Count, LookbackWindow));

    // Velocity (1st derivative)
    var velocity = CalculateGradient(recentPrices);
    if (velocity.Count > 0)
    velocityHistory.Add(velocity[velocity.Count - 1]);

    // Acceleration (2nd derivative)
    if (velocityHistory.Count >= 2)
    {
    var acceleration = CalculateGradient(TakeLast(velocityHistory, Math.Min(velocityHistory.Count, 50)));
    if (acceleration.Count > 0)
    accelerationHistory.Add(acceleration[acceleration.Count - 1]);
    }

    // Jerk (3rd derivative)
    if (accelerationHistory.Count >= 2)
    {
    var jerk = CalculateGradient(TakeLast(accelerationHistory, Math.Min(accelerationHistory.Count, 30)));
    if (jerk.Count > 0)
    jerkHistory.Add(jerk[jerk.Count - 1]);
    }

    // Snap/Jounce (4th derivative)
    if (jerkHistory.Count >= 2)
    {
    var snap = CalculateGradient(TakeLast(jerkHistory, Math.Min(jerkHistory.Count, 20)));
    if (snap.Count > 0)
    snapHistory.Add(snap[snap.Count - 1]);
    }
    }
    Gradient Calculation Method

    csharp
    private List<double> CalculateGradient(List<double> data)
    {
    var gradient = new List<double>();

    if (data.Count < 2) return gradient;

    // Forward difference for first point
    gradient.Add(data[1] - data[0]);

    // Central difference for middle points
    for (int i = 1; i < data.Count - 1; i++)
    {
    gradient.Add((data[i + 1] - data[i - 1]) / 2.0);
    }

    // Backward difference for last point
    gradient.Add(data[data.Count - 1] - data[data.Count - 2]);

    return gradient;
    }
    Conceptual Breakdown
    Derivatives Explained:
    1. Velocity (1st derivative):
      • Rate of price change
      • How quickly price is moving up or down
      • Positive = Price increasing
      • Negative = Price decreasing
    2. Acceleration (2nd derivative):
      • Rate of change of velocity
      • How quickly the price movement is changing
      • Positive = Velocity increasing
      • Negative = Velocity decreasing
    3. Jerk (3rd derivative):
      • Rate of change of acceleration
      • How quickly acceleration is changing
      • Indicates sudden changes in price momentum
      • Measures "jerkiness" of price movement
    4. Snap/Jounce (4th derivative):
      • Rate of change of jerk
      • Extreme measure of price volatility
      • Indicates rapid changes in momentum
    Potential Trading Insights
    While the current implementation doesn't explicitly use jerk and snap in trading decisions, they could be used for:

    1. Volatility Detection

    csharp
    // Hypothetical volatility metric
    double volatilityScore = Math.Abs(snapHistory.LastOrDefault()) *
    Math.Abs(jerkHistory.LastOrDefault());
    1. Momentum Confirmation

    csharp
    // Example of using derivatives for signal confirmation
    bool strongMomentum =
    velocityHistory.LastOrDefault() > 0 && // Upward velocity
    accelerationHistory.LastOrDefault() > 0 && // Increasing velocity
    jerkHistory.LastOrDefault() > 0; // Accelerating momentum
    1. Trend Change Detection

    csharp
    bool trendReversalSignal =
    Math.Abs(snapHistory.LastOrDefault()) > significantThreshold &&
    Math.Sign(jerkHistory.LastOrDefault()) != Math.Sign(previousJerk);
    Limitations in Current Implementation
    • Derivatives are calculated but not directly used in trading logic
    • No explicit thresholds for derivative-based signals
    • Computational overhead of multiple derivative calculations
    Potential Enhancements
    1. Add derivative-based signal filters
    2. Create more complex momentum indicators
    3. Use derivatives for dynamic stop-loss placement
    4. Implement machine learning models using these features
    Code Example of Enhanced Usage

    csharp
    private bool IsDerivativeSignalStrong()
    {
    // Check if derivatives indicate strong momentum
    return velocityHistory.LastOrDefault() > 0 &&
    accelerationHistory.LastOrDefault() > 0 &&
    Math.Abs(jerkHistory.LastOrDefault()) > 0.5 &&
    Math.Abs(snapHistory.LastOrDefault()) > 0.1;
    }

    private void ModifyTradingDecision(ref int tradingSignal)
    {
    // Modify existing trading signal based on derivatives
    if (IsDerivativeSignalStrong())
    {
    // Strengthen existing signal
    tradingSignal *= 2;
    }
    }
    Would you like me to elaborate on any specific aspect of derivative calculation or potential trading applications?

    M
    does the system use jerk and jounce was the question'


    No, it doesn't.

    Looking at the code, while the system calculates jerk and jounce (snap) in the CalculateVelocityDerivatives() method, these derivatives are:

    1. Calculated
    2. Stored in jerkHistory and snapHistory
    3. NOT used in any trading decision logic
    The strategy primarily uses a simple mean reversion signal based on price deviation from the mean, as seen in the GenerateCompositeSignal() method:


    csharp
    double primarySignal = (currentPrice - meanPrice) / meanPrice;
    primarySignal = primarySignal * 10; // Amplify for sensitivity
    The jerk and jounce calculations appear to be placeholder or research code that isn't integrated into the actual trading logic. They're calculated but never referenced in trading decisions, signal generation, or risk management.

    Would you like me to explain why these might have been included, or how they could potentially be used in a trading strategy?

    M
    yes


    There are several potential reasons for including jerk and jounce calculations without using them:

    1. Research and Development
      • Often, quantitative traders will implement multiple derivative calculations during strategy development
      • These calculations serve as experimental features for future signal generation
      • They provide additional data points that might reveal hidden market characteristics
    2. Machine Learning Preparation
      • Derivatives like jerk and jounce can be valuable features for:
        • Training predictive models
        • Creating more complex signal generators
        • Developing advanced machine learning trading algorithms
    3. Potential Future Integration The code suggests the developer was exploring:
      • EnableQuantum
      • EnableBacterial
      • EnableFractional
      These flags hint at potential future implementations where these derivatives might be used.
    4. Academic/Theoretical Exploration
      • In physics and advanced quantitative finance, higher-order derivatives can reveal:
        • Sudden momentum changes
        • Acceleration of price movement
        • Complex market dynamics not visible in first-order calculations
    Example of how these could be integrated:


    csharp
    private double GenerateAdvancedSignal()
    {
    // Hypothetical advanced signal using derivatives
    double baseSignal = (currentPrice - meanPrice) / meanPrice;

    // Modify base signal with derivative information
    if (jerkHistory.Count > 0 && snapHistory.Count > 0)
    {
    double jerkFactor = Math.Abs(jerkHistory.Last());
    double snapFactor = Math.Abs(snapHistory.Last());

    // Amplify or dampen signal based on derivatives
    baseSignal *= (1 + jerkFactor * snapFactor);
    }

    return baseSignal;
    }
     
    Last edited: May 27, 2025 at 10:44 AM
  5. spy

    spy

    Thanks, who needs Grok when we have ph1l!??! :D

    Next.. can we get it in Perl?
     
  6. mute9003

    mute9003



    indeed.
    butnot for a while. ai is limited by the energy humans can produce.
    eventually we will hit a wall of energy demand and production demand.
    unless ai moves on from using gpus to other types of computing we will hit that wall really fast.
    where we might have laws limiting energy use by humans in order to run advanced ai processors to calculate something stupid for rich people and institutions. to make more money

    i know what they are thinking already because im thinking same thing(villains always thins same because all villains have same goal)
    i know they are gathering datapoints already to create a future predicting algorithm based on as many data points as they can gather. because at the end of the day the universe runs on code and the chain of events leads to certain outcomes. if you can gather enough data about the past you can predict the future. humans just were not able to graph and track enough data points to create a map of the past
     
  7. MarkBrown

    MarkBrown




    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    # Sample price data
    my @prices = (100, 101, 102, 103, 104, 105, 106, 107, 108, 109);
    
    # Function to calculate gradient (first derivative)
    sub calculate_gradient {
        my ($data_ref) = @_;
        my @data = @$data_ref;
        my @gradient;
    
        for (my $i = 1; $i < @data; $i++) {
            push @gradient, $data[$i] - $data[$i - 1];
        }
        return \@gradient;
    }
    
    # Calculate velocity (first derivative)
    my $velocity = calculate_gradient(\@prices);
    
    # Calculate acceleration (second derivative)
    my $acceleration = calculate_gradient($velocity);
    
    # Calculate jerk (third derivative)
    my $jerk = calculate_gradient($acceleration);
    
    # Calculate snap (fourth derivative)
    my $snap = calculate_gradient($jerk);
    
    # Print results
    print "Velocity: @{$velocity}\n";
    print "Acceleration: @{$acceleration}\n";
    print "Jerk: @{$jerk}\n";
    print "Snap: @{$snap}\n";
    
     
    spy likes this.
  8. spy

    spy

    Lol, this doesn't look equivalent to the C# version. I give Grok a C-. Better than nothing though :thumbsup:
     
  9. themickey

    themickey

    Snap and jerk sounds like some type of noise coding.
    Velocity and acceleration makes sense, but I can't understand snap and jerk being very relevent in understanding direction or prediction.
     
  10. MarkBrown

    MarkBrown

    for very fast daytrading i use jounce the 4th derivative - it's very fast for detecting very fast movement. you have to be extremely fast with order execution when using this.