Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Real-Time Market Reasoning in AmiBroker Using Cerebras – The World’s Fastest AI Inference Engine

7 min read

Imagine your trading chart not just showing you price and indicators — but actually talking back with insights. By integrating Cerebras, the world’s fastest AI inference engine, into AmiBroker, traders can now ask real-time questions like “What does RSI 80 with a rising market mean?” and receive instant, plain-English reasoning. This transforms static indicators into intelligent, actionable feedback, displayed right inside your chart — complete with voice alerts and customizable prompts.

Beyond just interpretation, this opens the door to deeper automation and smarter decision-making. Traders can generate market commentaries, summarize strategy performance, or even screen multiple symbols with AI commentary — all with lightning-fast, cost-effective responses from Cerebras.

Welcome to the future of technical analysis, where Cerebras AI, the world’s fastest inference engine, is now natively integrated into AmiBroker using real-time prompts. This is not just another script — it’s a leap into AI-powered charting, capable of making sense of market momentum, divergences, and volatility patterns in under one second.

What is Cerebras?

Cerebras Systems is an AI hardware and software company known for building the world’s fastest AI inference and training systems, specifically engineered for large-scale deep learning models like GPT, LLaMA, and others.

At its core, Cerebras created the Wafer-Scale Engine (WSE) — the largest and most powerful processor chip ever made. Instead of using small GPU chips like NVIDIA, Cerebras builds an entire silicon wafer-sized chip (WSE-3) with:

  • 900,000 compute cores
  • 44 GB on-chip SRAM (ultra-fast memory)
  • 20x faster inference vs traditional GPU setups
  • Zero need for model sharding or memory offloading

They offer this compute power via:

  • Dedicated on-prem AI servers (CS-3 systems)
  • Cloud-based inference API (cloud.cerebras.ai)

In short: Cerebras is like the SpaceX of AI hardware — it’s pushing speed, efficiency, and scale to the extreme, making it perfect for real-time reasoning, especially in environments like trading systems where latency and cost matter.

What Can It Do Inside AmiBroker?

Using the two AFL snippets you’ve provided, traders can:

1. Cerebras AI – Send/Receive Simple Prompts from Amibroker

Prompt:

“RSI is 80, markets have been bullish for 10 days, what now?”

Response:

“Overbought condition suggests short-term correction, but uptrend may persist…”

The Tech That Makes It Possible

This is enabled by:

  • InternetPostRequest & JSON parsing in AFL.
  • A dynamic GFX model card showing inference config.
  • An interactive interface with ParamTrigger, Say(), and voice alerts.
  • Advanced token wrapping and alignment logic for visual clarity.
_SECTION_BEGIN("Cerebras AI Chat Integration with Model Card in GFX Table");

Version(6.4);
RequestTimedRefresh(1, False);

// Define parameter controls
apikey = ParamStr("Cerebras API Key", "xxxxxxxxxxxxxx");
model = ParamStr("Model", "llama-4-scout-17b-16e-instruct");
message = ParamStr("Message", "Current RSI is 80 and Markets are Rising for the last 10 days. What does it means?");

host = ParamStr("API Host", "https://api.cerebras.ai");
ver = ParamStr("API Version", "v1");

VoiceAlert = ParamList("Voice Alert", "Disable|Enable", 1);
trigger = Paramtrigger("Send Prompt", "Send");

// Construct URL
url = host + "/" + ver + "/chat/completions";

// Global response holders
globalPrompt = message;
globalResponse = "";
parsedContent = "";

// Function to extract choices[0].message.content from JSON string
function ExtractCerebrasReply(jsonStr)
{
    result = "";
    pattern = "\"content\":\"";
    start = StrFind(jsonStr, pattern);
    if (start >= 0)
    {
        start = start + StrLen(pattern);
        end = start;
        maxLen = StrLen(jsonStr);
        while (end < maxLen && StrMid(jsonStr, end, 1) != "\"")
        {
            end++;
        }
        result = StrMid(jsonStr, start-1, end - start);
    }
    return result;
}

// Function to Send Prompt
function SendCerebrasPrompt() {
    postData =
    "{\n" +
    "  \"model\": \"" + model + "\",\n" +
    "  \"stream\": false,\n" +
    "  \"max_tokens\": 50,\n" +
    "  \"temperature\": 0.2,\n" +
    "  \"top_p\": 1,\n" +
    "  \"messages\": [\n" +
    "    { \"role\": \"system\", \"content\": \"You are a helpful trading assistant. Provide Response in Plain text as I will be using inside Amibroker. So provie shorter response always\" },\n" +
    "    { \"role\": \"user\", \"content\": \"" + message + "\" }\n" +
    "  ]\n" +
    "}";

    headers = "Content-Type: application/json\r\n" +
              "Authorization: Bearer " + apikey + "\r\n";

    InternetSetHeaders(headers);
    _TRACE("Sending Prompt to Cerebras...");
    _TRACE(postData);

    ih = InternetPostRequest(url, postData);

    if (ih) {
        globalResponse = "";
        while ((line = InternetReadString(ih)) != "") {
            globalResponse += line;
        }
        _TRACEF("Response Received: %s", globalResponse);
        parsedContent = ExtractCerebrasReply(globalResponse);
        StaticVarSetText("promptresponse",parsedContent);
        _TRACE(parsedContent);
        if (VoiceAlert == "Enable") Say("Prompt sent successfully.");
        InternetClose(ih);
    } else {
        _TRACE("Failed to contact Cerebras API");
        parsedContent = "Error contacting Cerebras API";
    }
}

if (trigger) {
    SendCerebrasPrompt();
}

// -------------------- GFX Table Drawing ---------------------
cellHeight = 25;
cellWidth = 250;
startX = 20;
startY = 130;

function TableCell(text, col, row, bgColor, textColor)
{
    x1 = startX + (col - 1) * cellWidth;
    y1 = startY + (row - 1) * cellHeight;
    x2 = x1 + cellWidth;
    y2 = y1 + cellHeight;

    GfxSelectPen(colorBlue, 1);
    GfxSelectSolidBrush(bgColor);
    GfxRectangle(x1, y1, x2, y2);

    GfxSetBkColor(bgColor);
    GfxSetTextColor(textColor);
    GfxSetTextAlign(6);
    GfxTextOut(text, (x1 + x2)/2, (y1 + y2)/2 - 6);
}

// -------------------- GFX Output ----------------------------
GfxSelectFont("Arial", 12, 700);
GfxSetBkMode(1);
GfxSetTextColor(colorWhite);
GfxTextOut("Prompt: " + globalPrompt, 20, 40);
GfxSetTextColor(colorYellow);
GfxTextOut("Response:", 20, 70);
GfxSetTextColor(colorGreen);
GfxTextOut(StaticVarGetText("promptresponse"), 20, 90);

// GFX Table: Model Card
TableCell("Model Provider", 1, 1, colorBlue, colorWhite);
TableCell("Cerebras AI", 2, 1, colorBlack, colorWhite);
TableCell("Model Name", 1, 2, colorBlue, colorWhite);
TableCell(model, 2, 2, colorBlack, colorWhite);
TableCell("Inference Engine", 1, 3, colorBlue, colorWhite);
TableCell("Cerebras", 2, 3, colorBlack, colorWhite);
TableCell("Max Tokens", 1, 4, colorBlue, colorWhite);
TableCell("50", 2, 4, colorBlack, colorWhite);
TableCell("Temperature", 1, 5, colorBlue, colorWhite);
TableCell("0.2", 2, 5, colorBlack, colorWhite);
TableCell("Top-P", 1, 6, colorBlue, colorWhite);
TableCell("1", 2, 6, colorBlack, colorWhite);

_SECTION_END();

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

2. Cerebras AI – Current Market from Amibroker to Cerebras for Reasoning

Send Cerebras AI this:

Provide brief market outlook
RSI 14 is 52.0, ATR 14 is 293.44, MACD is bearish, SMA 50 is 24092.24, SMA 100 is 23577.38, SMA 200 is 24131.42 for NIFTY_I.
Today OHLC: O 24835.00, H 24929.00, L 24631.00, C 24654.00 |
Prev Day OHLC: O 24799.00, H 24869.00, L 24610.00, C 24826.30

Get this prompt response back with reasoning on the current market data:

Here is a brief market outlook based on the provided indicators and price action:

Key Points:

  1. RSI (14): 52.0 – Neutral, not overbought or oversold.
  2. ATR (14): 293.44 – Volatility is moderate.
  3. MACD: Bearish – Suggests a potential downtrend.
  4. SMA 50: 24092.24 – Price is above 50-period moving average.
  5. SMA 100: 23577.38 – Price is above 100-period moving average.
  6. SMA 200: 24131.42 – Price is close to 200-period moving average.

Price Action:

  1. Today’s Range: 24835.00 (H) to 24631.00 (L) – Narrow range.
  2. Close: 24654.00 – Below previous day’s close (24826.30).

Outlook:

Resistance levels: 24835.00, 24929.00 (H)

Bearish bias due to MACD and today’s close below previous day’s close.

Support levels: 24631.00 (L), 24092.24 (SMA 50).

All rendered inside the chart window, with a GFX dashboard and dynamic prompts.

_SECTION_BEGIN("Cerebras AI Market Snapshot");

Version(6.4);

RequestTimedRefresh(1, False);

Title = "Amibroker Realtime Prompt Engineer";

// User-defined parameters
apikey = ParamStr("Cerebras API Key", "xxxxxxxxxxxxxxxxxx");
modelName = ParamStr("Model", "llama-4-scout-17b-16e-instruct");
hostURL = ParamStr("API Host", "https://api.cerebras.ai");
apiVersion = ParamStr("API Version", "v1");
VoiceAlert = ParamList("Voice Alert", "Disable|Enable", 1);
trigger = ParamTrigger("Send Snapshot Prompt", "Send");

// === Market Snapshot Technical Indicators ===
rsiVal = RSI(14);
atrVal = ATR(14);
macdVal = MACD();
macdSig = Signal();
macdDelta = macdVal - macdSig;
macdTrend = WriteIf(macdDelta > 0, "bullish", "bearish");
sma_50 = MA(Close, 50);
sma_100 = MA(Close, 100);
sma_200 = MA(Close, 200);

// Get 1-bar ago OHLC values
open1  = Ref(Open, -1);
high1  = Ref(High, -1);
low1   = Ref( Low, -1);
close1 = Ref(Close, -1);

// Today's OHLC (current bar)
open0  = Open;
high0  = High;
low0   = Low;
close0 = Close;

// Construct dynamic message
message = 
    StrFormat("Provide brief market outlook. \\n\\nRSI 14 is %.1f, ATR 14 is %.2f, MACD is %s, SMA 50 is %.2f, SMA 100 is %.2f, SMA 200 is %.2f for %s. \\n\\nToday OHLC: O %.2f, H %.2f, L %.2f, C %.2f |\\n\\n Prev Day OHLC: O %.2f, H %.2f, L %.2f, C %.2f",
    LastValue(rsiVal), LastValue(atrVal), macdTrend,
    LastValue(sma_50), LastValue(sma_100), LastValue(sma_200), Name(),
    LastValue(open0), LastValue(high0), LastValue(low0), LastValue(close0),
    LastValue(open1), LastValue(high1), LastValue(low1), LastValue(close1));


// Construct API URL
url = hostURL + "/" + apiVersion + "/chat/completions";
globalPrompt = message;
globalResponse = "";
parsedContent = "";

// Extract reply from JSON
function ExtractCerebrasReply(jsonStr)
{
    result = "";
    pattern = "\"content\":\"";
    start = StrFind(jsonStr, pattern);
    if (start >= 0)
    {
        start = start + StrLen(pattern);
        end = start;
        maxLen = StrLen(jsonStr);
        while (end < maxLen && StrMid(jsonStr, end, 1) != "\"")
        {
            end++;
        }
        result = StrMid(jsonStr, start-1, end - start);
    }
    return result;
}

// Send prompt function
function SendCerebrasPrompt() {
    postData =
    "{\n" +
    "  \"model\": \"" + modelName + "\",\n" +
    "  \"stream\": false,\n" +
    "  \"max_tokens\": 300,\n" +
    "  \"temperature\": 0.2,\n" +
    "  \"top_p\": 1,\n" +
    "  \"messages\": [\n" +
    "    { \"role\": \"system\", \"content\": \"You are a helpful trading assistant. Provide Response in Plain text as I will be using inside Amibroker. Provide point by Point Summary \" },\n" +
    "    { \"role\": \"user\", \"content\": \"" + message + "\" }\n" +
    "  ]\n" +
    "}";

    headers = "Content-Type: application/json\r\n" +
              "Authorization: Bearer " + apikey + "\r\n";

    InternetSetHeaders(headers);
    _TRACE("Sending Prompt to Cerebras...");
    _TRACE(postData);

    ih = InternetPostRequest(url, postData);
    if (ih) {
        globalResponse = "";
        while ((line = InternetReadString(ih)) != "") {
            globalResponse += line;
        }
        _TRACEF("Response Received: %s", globalResponse);
        parsedContent = ExtractCerebrasReply(globalResponse);
        parsedContent = StrReplace(parsedContent,"","");
        
        StaticVarSetText("promptresponse", parsedContent);
        _TRACE(parsedContent);
        if (VoiceAlert == "Enable") Say("Prompt sent successfully.");
        InternetClose(ih);
    } else {
        _TRACE("Failed to contact Cerebras API");
        parsedContent = "Error contacting Cerebras API";
    }
}

if (trigger) {
    SendCerebrasPrompt();
}

// === GFX Dashboard Output with Wrapped Response ===
function DrawWrappedText(text, x, yStart, maxCharsPerLine, lineSpacing, textColor)
{
    GfxSetTextColor(textColor);
    GfxSetTextAlign(0); // left aligned

    lineCount = 0;
    tokenIndex = 0;
    text = StrReplace(text,"**","");
    text = StrReplace(text,"\\n\\n","^");
    text = StrReplace(text,"\\n","^");
    
    //text = StrReplace(text,"^1",":");
 
    token = StrExtract(text, tokenIndex,'.');
    line = "";

    while (token != "")
    {
        if (StrLen(line + " " + token) > maxCharsPerLine)
        {
			line = StrReplace(line,"^1","");
			line = StrReplace(line,"Summary","");
			line = StrReplace(line,"^: :","");
			line = StrReplace(line,"^:","");
			
            GfxTextOut(line, x, yStart + lineCount * lineSpacing);
            line = token;
            lineCount++;
        }
        else
        {
            line = WriteIf(line == "" , token , line + " " + token);
        }
        tokenIndex++;
        token = StrExtract(text, tokenIndex, '^');
    }

    if (line != "")
        GfxTextOut(line, x, yStart + lineCount * lineSpacing);
}

GfxSelectFont("Arial", 12, 700);
GfxSetBkMode(1);
GfxSetTextColor(colorYellow);
GfxTextOut("Prompt:", 20, 40);
DrawWrappedText(globalPrompt, 20, 60, 90, 20, colorred);
GfxSetTextColor(colorYellow);
GfxTextOut("Response:", 20, 160);
responseText = StaticVarGetText("promptresponse");
DrawWrappedText(responseText, 20, 180, 90, 20, colorGreen);

_SECTION_END();

//_SECTION_BEGIN("Price");
//SetChartOptions(0,chartShowArrows|chartShowDates);
//_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
//Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
//_SECTION_END();

Getting Started (Quick Guide)

  1. Register at cloud.cerebras.ai and grab your API Key.
  2. Paste it into the AFL editor via ParamStr("Cerebras API Key", ...)
  3. Load either:
    • Cerebras Chat GFX for prompts + model cards
    • Cerebras Market Snapshot for daily automated outlooks
  4. Click “Send Prompt” — and receive instant AI-driven market interpretation.

Who Is This For?

  • Scalpers who want intrabar interpretation before taking a position.
  • Quant traders building reasoning into entry-exit systems.
  • Portfolio managers who want macro + technical blends.
  • Students testing prompt engineering in real-time market data.
  • Bot builders using Cerebras to automate alerts, commentary, or AI dashboards.

Final Word

This isn’t just an AI add-on. It’s a fundamental upgrade to how technical traders interpret markets. With Cerebras and AmiBroker, we now have low-latency AI embedded directly into charts.

And guess what?

🟢 It speaks.
🟢 It listens.
🟢 It reasons.

It’s time to build with Cerebras inside AmiBroker.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More