Advertisement IC Markets

The one indicator I still trust for bias only

Discuss 1-minute to 15-minute price action setups, fading intraday momentum, key support/resistance zones, and proven short-term trading methodologies.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

4. cBot Integration

Now, update the cBot to instantiate your chosen logger and inject it into the TryExecuteTrade facade.

Code: Select all

using cAlgo.API;

namespace cAlgo.Robots
{
    // CRITICAL: FullAccess is required for System.Data.SqlClient and HttpClient
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class RegimeExecutionGuard : Robot
    {
        private ProRegimeBias _biasIndicator;
        private IRejectionLogger _telemetryLogger;

        protected override void OnStart()
        {
            // Initialize indicator
            _biasIndicator = Indicators.GetIndicator<ProRegimeBias>(/* params */);

            // Select your logging destination:
            
            // Option A: Local MS SQL
            string sqlString = "Server=localhost;Database=AlgoTelemetry;Integrated Security=True;";
            _telemetryLogger = new SqlRejectionLogger(sqlString);

            // Option B: Azure Webhook
            // string endpoint = "https://your-azure-function-url.azurewebsites.net/api/LogRejection";
            // _telemetryLogger = new WebhookRejectionLogger(endpoint);
        }

        private bool TryExecuteTrade(TradeType requestedDirection, string label)
        {
            RegimeState currentState = _biasIndicator.CurrentRegime;
            bool isAllowed = false;
            string rejectionReason = string.Empty;

            // ... (Regime validation logic remains exactly the same) ...

            if (!isAllowed)
            {
                // 1. Log locally to the cTrader journal
                Print($"[ORDER REJECTED] {requestedDirection} | {rejectionReason}");
                
                // 2. Fire telemetry to SQL / Azure
                _telemetryLogger.LogRejectionAsync(
                    SymbolName, 
                    requestedDirection.ToString(), 
                    currentState.ToString(), 
                    rejectionReason
                );
                
                return false;
            }

            // Execute the trade...
            return true;
        }
    }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

Bridging your local MS SQL Server directly to a Python-based CrewAI workflow is a highly efficient way to analyze trading behavior without exposing your data to third-party cloud APIs.

Since you are running this locally on a workstation with an NVIDIA RTX GPU, Ollama will natively hardware-accelerate the inference, making it fast enough to run complex multi-agent reasoning on your daily rejection logs.

Instead of manually exporting CSVs, you can wire Python directly to your SQL database using pyodbc. Here is the architecture for an automated post-session analysis pipeline.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

Step 1: Extract Data from MS SQL

First, write a Python script to query your TradeRejections table. This pulls the day's automated rejections into a pandas DataFrame and formats them into a single text block that the AI agents can digest.

Code: Select all

import pyodbc
import pandas as pd

# Connect to your local MS SQL database
conn_str = (
    "DRIVER={ODBC Driver 17 for SQL Server};"
    "SERVER=localhost;"
    "DATABASE=AlgoTelemetry;"
    "Trusted_Connection=yes;"
)
conn = pyodbc.connect(conn_str)

# Extract today's rejected trades
query = """
    SELECT Timestamp, Symbol, Direction, Regime, Reason 
    FROM TradeRejections 
    WHERE CAST(Timestamp AS DATE) = CAST(GETUTCDATE() AS DATE)
"""
df = pd.read_sql(query, conn)
conn.close()

# Format the data for the LLM prompt
rejection_log_text = df.to_string(index=False)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

Step 2: Configure the Local AI Agents

Using CrewAI and LangChain's Ollama integration, we will spin up two distinct agents.

The Quant Analyst: Looks for statistical patterns (e.g., "70% of rejections happened during an Exhausted HTF regime").

The Trading Psychologist: Analyzes the behavioral implication (e.g., "You are repeatedly trying to counter-trend Gold when it is fundamentally overextended").

Code: Select all

from crewai import Agent, Task, Crew, Process
from langchain_community.llms import Ollama

# Bind to your local Ollama instance (ensure Ollama is running)
# Llama 3 or DeepSeek are excellent for logical deduction and coding analysis
local_llm = Ollama(model="llama3")

# Define the Agents
quant_agent = Agent(
    role="Quantitative Risk Manager",
    goal="Identify statistical patterns and structural vulnerabilities in rejected order flow.",
    backstory="An algorithmic risk manager who analyzes rejected trades to find recurring flaws in entry timing and regime alignment.",
    verbose=True,
    allow_delegation=False,
    llm=local_llm
)

psych_agent = Agent(
    role="Trading Psychologist",
    goal="Translate statistical trading errors into behavioral insights and actionable strictures.",
    backstory="A performance coach for professional scalpers. You identify FOMO, revenge trading, and counter-trend biases based on execution logs.",
    verbose=True,
    allow_delegation=False,
    llm=local_llm
)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

Step 3: Define the Tasks and Execute

Now, pass the formatted SQL data into the tasks and let the crew analyze your session.

Code: Select all

# Define the Tasks
analyze_data_task = Task(
    description=f"Analyze the following rejected trades log from today's session. Identify the most common regimes where trades are blocked and which symbols are causing the most discipline breaks.\n\nData:\n{rejection_log_text}",
    expected_output="A bulleted statistical summary of the rejected trades, highlighting the primary reasons and regimes involved.",
    agent=quant_agent
)

behavioral_review_task = Task(
    description="Review the quantitative analysis provided by the Risk Manager. Provide a blunt, 3-point behavioral assessment of what these mistakes say about the trader's mindset today, and one strict rule to apply tomorrow.",
    expected_output="A 3-point behavioral assessment and one actionable rule for the next trading session.",
    agent=psych_agent
)

# Assemble the Crew
trading_review_crew = Crew(
    agents=[quant_agent, psych_agent],
    tasks=[analyze_data_task, behavioral_review_task],
    process=Process.sequential
)

# Execute the workflow
print("Starting post-session AI analysis...")
result = trading_review_crew.kickoff()

print("\n### DAILY DEBRIEF ###\n")
print(result)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

The Workflow in Practice

You can schedule this Python script to run automatically at the end of your trading session (e.g., via Windows Task Scheduler at 5:00 PM). It will silently ping your SQL database, run the data through Ollama, and output a concise, brutally honest assessment of how many bad trades your C# guardrail saved you from taking.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

Yes. If you are scalping raw price action on 1-minute or 5-minute charts, logging the spread and order book thickness at the exact millisecond of rejection is the difference between generic trend analysis and true market microstructure analysis.

A higher-timeframe regime indicator tells you what is happening, but the spread and liquidity tell you how it is happening.

For example, if the HTF state is "Exhausted" and your order is rejected:

Scenario A (Normal Spread, Thick Book): The trend is simply losing momentum. Buyers are exhausted, and limit orders are stacking up against the move.

Scenario B (5x Widened Spread, Thin Book): This is toxic order flow. Institutional algorithms have pulled their liquidity to execute a violent sweep.

By feeding this into your local AI agents, the "Quantitative Risk Manager" can mathematically distinguish between a slow trend death and a dangerous stop-hunt, giving you highly specific feedback on the execution environment.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

1. Expanding the SQL Schema

We need to add columns to capture the spread in pips, and the volume sitting on the nearest levels of the order book (Ask and Bid).

Code: Select all

ALTER TABLE TradeRejections
ADD 
    SpreadInPips DECIMAL(10, 2) NULL,
    TopAskVolume BIGINT NULL,
    TopBidVolume BIGINT NULL;
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

2. Updating the cTrader Bot to Capture Microstructure

cTrader’s API provides direct, asynchronous access to Level 2 Market Depth. We need to initialize it in OnStart() and extract the top-of-book volume precisely when the trade is rejected.

Code: Select all

using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class RegimeExecutionGuard : Robot
    {
        // ... (existing parameters and variables) ...
        
        private MarketDepth _marketDepth;

        protected override void OnStart()
        {
            // ... (existing initialization) ...

            // Subscribe to Level 2 Market Depth for the current symbol
            _marketDepth = MarketData.GetMarketDepth(SymbolName);
        }

        private bool TryExecuteTrade(TradeType requestedDirection, string label)
        {
            RegimeState currentState = _biasIndicator.CurrentRegime;
            bool isAllowed = false;
            string rejectionReason = string.Empty;

            // ... (Regime validation logic) ...

            if (!isAllowed)
            {
                // Capture Microstructure snapshot at the millisecond of rejection
                double spreadInPips = Symbol.Spread / Symbol.PipSize;
                
                // Sum the volume of the top 3 levels of the order book to gauge immediate liquidity
                long topAskVol = (long)_marketDepth.AskEntries.Take(3).Sum(x => x.VolumeInUnits);
                long topBidVol = (long)_marketDepth.BidEntries.Take(3).Sum(x => x.VolumeInUnits);

                Print($"[REJECTED] {requestedDirection} | Spread: {spreadInPips:F1} | Reason: {rejectionReason}");
                
                // Route the expanded telemetry
                _telemetryLogger.LogRejectionAsync(
                    SymbolName, 
                    requestedDirection.ToString(), 
                    currentState.ToString(), 
                    rejectionReason,
                    spreadInPips,
                    topAskVol,
                    topBidVol
                );
                
                return false;
            }

            return true;
        }
    }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: The one indicator I still trust for bias only

Post by PTScalper »

3. Updating the SQL Logger Interface

The C# interface and SQL command must be expanded to accept the new microstructure parameters.

Code: Select all

public interface IRejectionLogger
{
    void LogRejectionAsync(string symbol, string direction, string regime, string reason, double spread, long askVol, long bidVol);
}

public class SqlRejectionLogger : IRejectionLogger
{
    // ... (connection string setup) ...

    public void LogRejectionAsync(string symbol, string direction, string regime, string reason, double spread, long askVol, long bidVol)
    {
        Task.Run(() =>
        {
            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();
                    string query = @"
                        INSERT INTO TradeRejections 
                        (Timestamp, Symbol, Direction, Regime, Reason, SpreadInPips, TopAskVolume, TopBidVolume) 
                        VALUES (@time, @sym, @dir, @regime, @reason, @spread, @askVol, @bidVol)";

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@time", DateTime.UtcNow);
                        command.Parameters.AddWithValue("@sym", symbol);
                        command.Parameters.AddWithValue("@dir", direction);
                        command.Parameters.AddWithValue("@regime", regime);
                        command.Parameters.AddWithValue("@reason", reason);
                        command.Parameters.AddWithValue("@spread", spread);
                        command.Parameters.AddWithValue("@askVol", askVol);
                        command.Parameters.AddWithValue("@bidVol", bidVol);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                cAlgo.API.Logger.Print($"SQL Logging Failed: {ex.Message}");
            }
        });
    }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply