Advertisement IC Markets

Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Share, develop, and backtest custom MQL4/MQL5 Expert Advisors, Python data-scraping scripts, trading bots, and automated market alert systems.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

Hi traders,

i got an idea to test local models from Gemma4 family on my working station.
I choose Gemma4 12B, 26B and 31B, im really interested what will be real differences.

1. The Core Architectural Differences

When generating niche, domain-specific code like TradingView's Pine Script, raw parameter count only tells half the story. The architecture dictates how the model retrieves syntax rules and manages logic.

Gemma 4 12B

Architecture: Dense
VRAM:~8-12 GB
Pine Script Advantage: Excellent baseline. Processes all 12B parameters per token for steady, predictable code generation.

Gemma 4 26B A4B

Architecture: Mixture of Experts (MoE)
VRAM:~16-24 GB
Pine Script Advantage: Extreme speed. Loads 26B into memory but only activates ~4B parameters per token.

Gemma 4 31B

Architecture: Mixture of Experts (MoE)
VRAM:~20-24+ GB
Pine Script Advantage: Deepest reasoning. Highest accuracy for complex time-series rules and strict typing.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

2. The MoE Trap: Why 26B A4B Might Behave Strangely

The Gemma 4 26B A4B is a Mixture of Experts (MoE) model. It holds 26 billion parameters but dynamically routes each token to specific "expert" subnetworks, activating only a small subset of parameters at a time.

For standard programming languages like Python or C#, MoE is incredibly efficient. However, Pine Script is a highly specialized language. If the model's router fails to activate the specific expert trained on Pine Script v5/v6 syntax, the active parameters might "panic" and hallucinate standard C-style arrays or Python logic—for example, trying to force standard for loops instead of using native time-series references like close[1].

When setting up your test workstation—like an HP Z1 G1i Tower—the 26B A4B will compute incredibly fast on the CPU because it calculates like a smaller 4B model. However, you will need to watch closely for syntactical hallucinations.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

3. The 31B Dense Advantage for Time-Series Logic

Pine Script's execution model is notoriously tricky for LLMs because it executes on every historical bar sequentially.

Repainting Bugs: Smaller or MoE models often write logic that looks ahead (e.g., evaluating close before a bar is confirmed), which causes repainting in live trading.

Type Strictness: Pine Script strictly distinguishes between a series float (changes per bar) and a simple float (constant).

Translation: Converting high-volume scalping logic from cTrader or MetaTrader 4/5 into Pine Script requires understanding entirely different execution environments.

The Gemma 4 31B is a fully dense model. Every single token processed runs through all 31 billion parameters. This brute-force contextual awareness makes it far less likely to lose track of Pine Script's strict typing system or accidentally introduce lookahead bias. The tradeoff is speed and hardware; the model files are massive, making a roomy, fast drive like a 4TB NVMe SSD critical for swift model loading and swapping during your tests.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

4. Context Window & RAG Potential

All three of these models boast massive context windows of up to 256K tokens. This is a significant advantage for your forum post because you don't have to rely purely on the model's pre-trained knowledge. You can dump the entire Pine Script Reference Manual, along with specific examples of your custom indicators, directly into the prompt.

A great testing angle for your readers would be to evaluate whether the lighter 12B model, heavily augmented with official Pine Script documentation in its prompt, can outperform the raw, zero-shot coding capabilities of the massive 31B model.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

Here is a stress-test prompt designed to expose whether a local model actually understands Pine Script's execution model or if it just hallucinates standard programming logic.

This prompt is deliberately structured to bait the LLM into making three of the most common repainting errors: multi-timeframe (MTF) lookahead bias, intrabar signal flickering, and drifting stop-losses.

The Test Prompt
Copy and paste this exact text into Gemma 4 12B, 26B, and 31B:

Code: Select all

Write a Pine Script v6 strategy for a 15-minute chart. 

The strategy should trigger a Long entry when the 15m Close crosses over the 15m 20-period EMA, but ONLY if the Daily timeframe's Close is currently above the Daily 50-period SMA.

Upon entry, calculate a Stop Loss at 1.5x the Daily ATR below the entry price, and a Take Profit at 3x the Daily ATR. 

[b]Requirements:[/b]
1. The strategy must be strictly non-repainting in a live market environment. 
2. Backtest results must perfectly match live execution.
3. Fire an alert when the entry condition is met, ensuring no false intrabar triggers.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

Output from Gemma 4 12B:

Thought for 178.8 seconds

Output:

To meet your requirements, I have developed a Pine Script v6 strategy.

Key Technical Features Included:

Non-Repainting MTF: Uses request.security with barmerge.lookahead_off to ensure that the Daily data used by the 15-minute chart is only data that was actually available at that specific moment in time.

Execution Integrity: By calculating the SL and TP based on the Daily ATR at the moment of the crossover, the orders are placed as firm limit/stop orders.
Alert System: Included an alert_message parameter that triggers a notification specifically when the entry conditions are met.

Code: Select all

//@version=6
strategy("15m EMA Cross + Daily Filter Strategy", 
     overlay=true, 
     initial_capital=10000, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=10, 
     commission_type=strategy.commission.commission_percent, 
     commission_value=0.03)

// --- Inputs ---
emaLength = input.int(20, "15m EMA Length", minval=1)
smaLength = input.int(50, "Daily SMA Length", minval=1)
atrLength = input.int(14, "Daily ATR Length", minval=1)
slMultiplier = input.float(1.5, "Stop Loss (x Daily ATR)")
tpMultiplier = input.float(3.0, "Take Profit (x Daily ATR)")

// --- Calculations ---
// 15m EMA
ema15m = ta.ema(close, emaLength)

// Requesting Daily Data (Non-Repainting)
// We fetch a tuple of the Daily SMA and Daily ATR to ensure they are synced
[daily_sma, daily_atr] = request.security(syminfo.tickerid, "D", [ta.sma(close, smaLength), ta.atr(atrLength)], lookahead=barmerge.lookahead_off)

// --- Logic ---
// Condition 1: 15m Close crosses over 15m 20-period EMA
crossUp = ta.crossover(close, ema15m)

// Condition 2: Daily Close is above Daily 50-period SMA
// Note: Since we are on the 15m chart, the "Current Daily Close" is the price of the current day.
daily_filter = close > daily_sma

// Entry Condition
longCondition = crossUp and daily_filter

// --- Execution ---
// Variables to store entry prices for SL/TP calculation
var float entry_price = 0.0
var float stop_loss = 0.0
var float take_profit = 0.0

if longCondition
    entry_price := close
    stop_loss := close - (daily_atr * slMultiplier)
    take_profit := close + (daily_atr * tpMultiplier)
    
    // The alert_message will be passed to the alert system
    strategy.entry("Long", strategy.long, alert_message = "Long Entry: Price " + str.tostring(close) + " SL: " + str.tostring(stop_loss) + " TP: " + str.tostring(take_profit))

// Exit Logic
// We use strategy.exit to set the SL and TP orders automatically
if strategy.position_size > 0
    strategy.exit("Exit_Long", "Long", stop=stop_loss, limit=take_profit, alert_message="Exit Order Executed")

// --- Visuals ---
plot(ema15m, color=color.blue, title="15m EMA 20")
plot(daily_sma, color=color.orange, title="Daily SMA 50 (Filtered)", display=display.none) // Hidden by default, but available for verification

// Visual highlights
plotshape(longCondition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Long Signal")

// Color the background when the Daily filter is active
bg_color = daily_filter ? color.new(color.green, 90) : color.new(color.red, 90)
bgcolor(bg_color, title="Daily Filter Active Zone")
Attachments
Snímek obrazovky 2026-09-09 132304.png
Snímek obrazovky 2026-09-09 132304.png (85.78 KiB) Viewed 267 times
Snímek obrazovky 2026-09-09 132254.png
Snímek obrazovky 2026-09-09 132254.png (118.31 KiB) Viewed 267 times
Snímek obrazovky 2026-09-09 132246.png
Snímek obrazovky 2026-09-09 132246.png (102.83 KiB) Viewed 267 times
Snímek obrazovky 2026-09-09 131616.png
Snímek obrazovky 2026-09-09 131616.png (56.29 KiB) Viewed 267 times
Snímek obrazovky 2026-09-09 131604.png
Snímek obrazovky 2026-09-09 131604.png (95.72 KiB) Viewed 267 times
Snímek obrazovky 2026-09-09 131556.png
Snímek obrazovky 2026-09-09 131556.png (48.4 KiB) Viewed 267 times
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

How this meets your requirements:

Non-Repainting: The request.security function is configured with barmerge.lookahead_off. This ensures that the 15m chart only "sees" the Daily SMA and ATR values that were confirmed at the start of the current day (or previous day), preventing signals from appearing/disappearing in the past.
Backtest Accuracy: By calculating the stop_loss and take_profit levels at the exact moment of entry and passing them into strategy.exit, the backtester treats them as hard stops/limits. This prevents the "floating" results common in scripts that calculate profit targets dynamically every bar.

Alerts:
I included alert_message inside the strategy.entry function.
When you set up the alert in TradingView, you can use the message {{strategy.order.alert_message}} in the alert box. This will ensure the alert contains the specific entry details.
Timeframe Compatibility: While it uses Daily data for the filter and the ATR calculation, the script is designed to be loaded on a 15-minute chart.
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

How to set up the Alert:

Add the script to your chart.
Select the 15m timeframe.
Click the "Alert" icon.
In the Condition dropdown, select the strategy.
In the Message box, use: {{strategy.order.alert_message}} (This ensures the dynamic SL/TP values are included in your push notification or email).


-----> here ends output from Gemma4 12B
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

Output from Gemma 4 26B:

Thought for 99 seconds

Output:

To ensure this strategy meets your strict requirements—specifically the non-repainting and no false intrabar trigger requirements—the script is designed to evaluate conditions only at the close of a bar.

In Pine Script, the most common cause of repainting in MTF (Multi-Timeframe) strategies is using lookahead=barmerge.lookahead_on. I have used lookahead=barmerge.lookahead_off, which ensures the 15m chart only sees Daily data that has already been "confirmed" (the previous day's close).

Code: Select all

//@version=6
strategy("Non-Repainting 15m EMA/Daily SMA Strategy", 
     overlay=true, 
     initial_capital=10000, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=10, 
     process_orders_on_close=true) // Ensures execution happens at the close to prevent intrabar false triggers

// --- Inputs ---
emaLength    = input.int(20, "15m EMA Length", minval=1)
dailySmaLen  = input.int(50, "Daily SMA Length", minval=1)
dailyAtrLen  = input.int(14, "Daily ATR Length", minval=1)
slMultiplier = input.float(1.5, "Stop Loss Multiplier (x ATR)")
tpMultiplier = input.float(3.0, "Take Profit Multiplier (x ATR)")

// --- Multi-Timeframe Data (Non-Repainting) ---
// We use lookahead_off to ensure we are only accessing data that was available at the time.
// request.security with lookahead_off returns the value of the LAST CLOSED daily bar.
[dClose, dSma, dAtr] = request.security(syminfo.tickerid, "D", [close[1], ta.sma(close, dailySmaLen)[1], ta.atr(dailyAtrLen)[1]], lookahead=barmerge.lookahead_off)

// --- 15m Indicators ---
ema15m = ta.ema(close, emaLength)

// --- Strategy Logic ---
// 1. 15m Close crosses over 15m 20-period EMA
// 2. Daily Close (last completed) is above Daily 50-period SMA
emaCrossUp = ta.crossover(close, ema15m)
dailyFilter = dClose > dSma

longCondition = emaCrossUp and dailyFilter

// --- Execution and Risk Management ---
// We use 'var' to lock in the SL and TP prices at the moment of entry 
// so they do not fluctuate with every subsequent bar.
var float stopLossPrice = 0.0
var float takeProfitPrice = 0.0

if longCondition
    // Calculate SL and TP based on the entry bar's close
    stopLossPrice   := close - (dAtr * slMultiplier)
    takeProfitPrice := close + (dAtr * tpMultiplier)
    
    // Alert message included in the strategy order
    alert_msg = "LONG ENTRY\nPrice: " + str.tostring(close) + "\nSL: " + str.tostring(stopLossPrice) + "\nTP: " + str.tostring(takeProfitPrice)
    
    strategy.entry("Long", strategy.long, alert_message=alert_msg)

// Exit logic: Using strategy.exit with fixed prices determined at entry
if strategy.position_size > 0
    strategy.exit("Exit Long", "Long", stop=stopLossPrice, limit=takeProfitPrice, comment_loss="SL", comment_profit="TP")

// --- Visuals ---
plot(ema15m, color=color.blue, title="15m EMA 20", linewidth=2)
plot(dSma, color=color.orange, title="Daily SMA 50 (Last Closed)", style=plot.style_linebr)

// Background color to indicate Daily Filter status
bgcolor(dailyFilter ? color.new(color.green, 90) : color.new(color.red, 90), title="Daily Trend Filter")

// Visualizing SL and TP levels for the current trade
plot(strategy.position_size > 0 ? stopLossPrice : na, color=color.red, style=plot.style_linebr, title="Active Stop Loss")
plot(strategy.position_size > 0 ? takeProfitPrice : na, color=color.green, style=plot.style_linebr, title="Active Take Profit")

// Visual marker for the entry signal
plotshape(longCondition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Long Signal")
Attachments
Snímek obrazovky 2026-09-09 132541.png
Snímek obrazovky 2026-09-09 132541.png (58.02 KiB) Viewed 265 times
Snímek obrazovky 2026-09-09 132532.png
Snímek obrazovky 2026-09-09 132532.png (112.96 KiB) Viewed 265 times
Snímek obrazovky 2026-09-09 132453.png
Snímek obrazovky 2026-09-09 132453.png (85.05 KiB) Viewed 265 times
Snímek obrazovky 2026-09-09 132910.png
Snímek obrazovky 2026-09-09 132910.png (40.76 KiB) Viewed 265 times
Snímek obrazovky 2026-09-09 132905.png
Snímek obrazovky 2026-09-09 132905.png (122.18 KiB) Viewed 265 times
Snímek obrazovky 2026-09-09 132858.png
Snímek obrazovky 2026-09-09 132858.png (110.28 KiB) Viewed 265 times
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: Local LLMs for Pine Script v6: Gemma 4 (12B vs. 26B MoE vs. 31B)

Post by PTScalper »

Technical Breakdown:

1. Non-Repainting & MTF Accuracy

The biggest danger in MTF scripts is "leaking" information from the future.

I used request.security with lookahead=barmerge.lookahead_off.
I specifically requested close[1] and ta.sma(...)[1] from the Daily timeframe. This ensures that when the 15-minute bar is trading, it is looking at the completed Daily candle. It cannot "know" the current daily close until the day is over, making the backtest 100% identical to live trading.

2. Preventing False Intrabar Triggers

I added process_orders_on_close=true to the strategy() declaration.
By default, Pine Script signals can appear mid-bar and disappear by the end of the bar. This setting forces the strategy to evaluate the logic at the moment the bar closes. An order is only triggered once the crossover is confirmed and the bar is finalized.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply