Instructions to use deepseek-ai/DeepSeek-V4.1-Flash with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use deepseek-ai/DeepSeek-V4.1-Flash with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="deepseek-ai/DeepSeek-V4.1-Flash") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash", device_map="auto") - Inference
- HuggingChat
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use deepseek-ai/DeepSeek-V4.1-Flash with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "deepseek-ai/DeepSeek-V4.1-Flash" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "deepseek-ai/DeepSeek-V4.1-Flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/deepseek-ai/DeepSeek-V4.1-Flash
- SGLang
How to use deepseek-ai/DeepSeek-V4.1-Flash with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "deepseek-ai/DeepSeek-V4.1-Flash" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "deepseek-ai/DeepSeek-V4.1-Flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "deepseek-ai/DeepSeek-V4.1-Flash" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "deepseek-ai/DeepSeek-V4.1-Flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use deepseek-ai/DeepSeek-V4.1-Flash with Docker Model Runner:
docker model run hf.co/deepseek-ai/DeepSeek-V4.1-Flash
Delete DeepSeek_V41_Tech_Report.pdf
the bot is making losses. make this bot high frequency bot and more profitable with 90% winrate. 20 pips between grid and 35 pips before starting.
//+------------------------------------------------------------------+
//| HORIZON_AI_BOT_HEDGE_SCALPER_V2.mq5|
//| HORIZON AI BOT |
//| High-frequency XAUUSD scalper with a DELAYED opposite hedge. |
//| |
//| Cycle: |
//| 1. Fast EMA bias picks a direction; N legs open that way with a |
//| small TP (high hit-rate by design) and a wide disaster stop. |
//| 2. If, after the delay (default 30 s), the legs are still |
//| underwater, the OPPOSITE side is opened with the same lots |
//| (lock) - no martingale, no extra size. |
//| 3. Release: price recovers -> hedge closed, primary runs to TP; |
//| price keeps falling -> primary closed, hedge trailed. |
//| 4. Timeouts flatten everything. Loss per cycle is bounded. |
//| |
//| The panel shows REAL cycle win rate, profit factor and net P/L - |
//| a high win rate means nothing unless profit factor is > 1. |
//| REQUIRES a HEDGING account. |
//+------------------------------------------------------------------+
#property copyright "HORIZON AI BOT"
#property link ""
#property version "2.00"
#property description "HORIZON AI BOT HEDGE SCALPER V2 - high-frequency scalper with delayed opposite hedge (hedging accounts only)"
#property strict
#include <Trade\Trade.mqh>
enum ENUM_LOT_MODE
{
LOT_FIXED = 0, // Fixed lots per leg
LOT_PERCENT = 1 // Risk % of equity per cycle (sized on the disaster stop)
};
//==================================================================
// INPUTS
//==================================================================
input group "=== General ==="
input long InpMagic = 20261126; // Magic number
input bool InpStrictSymbol = true; // Only trade XAU / GOLD symbols
input string InpTradeComment = "HORIZON-HEDGE2"; // Order comment
input group "=== Position sizing ==="
input ENUM_LOT_MODE InpLotMode = LOT_FIXED; // Sizing mode
input double InpFixedLot = 0.02; // Lots per leg
input double InpRiskPercent = 0.30; // Risk % per cycle if the disaster stop is hit
input double InpMaxLot = 1.00; // Hard lot cap per leg
input int InpLegsPerSide = 3; // Legs per side (1-5)
input group "=== Direction bias (M1 EMAs) ==="
input int InpFastEMA = 5; // Fast EMA
input int InpSlowEMA = 20; // Slow EMA
input double InpMinBiasAtr = 0.10; // Min EMA separation (ATR) - avoids chop
input group "=== Cycle logic (ATR = M1) ==="
input int InpATRPeriod = 14; // ATR period (M1)
input double InpTPAtr = 0.50; // Leg 1 take profit (ATR)
input double InpLegTPStep = 0.50; // Extra TP per leg index (x leg-1 TP)
input double InpHardSLAtr = 1.50; // Disaster stop on every leg (ATR)
input int InpHedgeDelaySeconds = 30; // Delay before the opposite side may be placed
input bool InpHedgeRequireAdverse = true; // Hedge only if primary is underwater
input double InpHedgeTriggerAtr = 0.30; // ...by at least this much (ATR)
input double InpReleaseAtr = 0.40; // Move from hedge price that releases the lock (ATR)
input double InpTrailAtr = 0.40; // Trailing distance for the surviving side (ATR)
input double InpTrailStepAtr = 0.05; // Min trailing step (ATR)
input int InpMaxPrimarySeconds = 120; // Unhedged primary max life (s)
input int InpLockMaxSeconds = 90; // Max time to stay locked (s)
input int InpMaxHoldSeconds = 300; // Max life of a released cycle (s)
input group "=== Frequency ==="
input int InpCooldownSeconds = 3; // Wait between cycles (s)
input int InpMaxCyclesPerMinute = 6; // Cap on new cycles per minute
input int InpMaxCyclesPerDay = 1000; // Cap on new cycles per day
input group "=== Entry filters ==="
input double InpMinATRPoints = 80; // Min ATR (points)
input double InpMaxATRPoints = 1500; // Max ATR (points)
input double InpMaxSpreadPoints = 35; // Max spread (points)
input double InpMaxSpreadTPFrac = 0.30; // Max spread as fraction of the TP distance
input int InpSlippagePoints = 20; // Max deviation (points)
input group "=== Session filter (BROKER server time) ==="
input bool InpUseSessionFilter = true; // Enable session filter
input int InpSessionStartHour = 7; // Session start hour
input int InpSessionEndHour = 20; // Session end hour
input group "=== News filter ==="
input bool InpUseNewsFilter = true; // Enable economic calendar filter
input int InpNewsMinutesBefore = 15; // Block minutes before high-impact news
input int InpNewsMinutesAfter = 15; // Block minutes after high-impact news
input string InpNewsCurrency = "USD"; // News currency to watch
input group "=== Prop-firm / risk protection ==="
input double InpMaxDailyLossPercent = 3.00; // Max daily loss % (equity)
input double InpMaxTotalDDPercent = 8.00; // Max drawdown % from peak equity
input int InpMaxConsecLosses = 5; // Pause after N losing cycles (0 = off)
input int InpPauseMinutes = 30; // Pause length (minutes)
//==================================================================
// GLOBALS
//==================================================================
CTrade trade;
int g_atrHandle = INVALID_HANDLE;
int g_fastHandle = INVALID_HANDLE;
int g_slowHandle = INVALID_HANDLE;
double g_point = 0.0;
int g_digits = 2;
//--- cycle state: 0 none, 1 primary only, 2 locked (hedged), 3 released
int g_phase = 0;
int g_primaryDir = 0; // 1 buy, -1 sell
int g_winnerDir = 0;
datetime g_cycleStart = 0;
datetime g_hedgeTime = 0;
double g_entry = 0.0;
double g_hedgePrice = 0.0;
double g_atrOpen = 0.0;
double g_lot = 0.0;
double g_cyclePnl = 0.0;
datetime g_lastCycleEnd = 0;
//--- counters / stats
int g_cyclesToday = 0;
long g_minuteStamp = -1;
int g_minuteCycles = 0;
int g_wins = 0;
int g_losses = 0;
double g_grossWin = 0.0;
double g_grossLoss = 0.0;
//--- guards
int g_lastDay = -1;
double g_dayStartEquity = 0.0;
double g_peakEquity = 0.0;
bool g_dayHalted = false;
bool g_ddHalted = false;
int g_consecLosses = 0;
datetime g_pauseUntil = 0;
bool g_newsBlocked = false;
datetime g_lastNewsCheck = 0;
//==================================================================
// HELPERS
//==================================================================
double NormalizePrice(const double p)
{
return NormalizeDouble(p, g_digits);
}
bool IsValidSymbol()
{
if(!InpStrictSymbol)
return true;
string s = _Symbol;
StringToUpper(s);
return (StringFind(s, "XAU") >= 0 || StringFind(s, "GOLD") >= 0);
}
double GetATR()
{
double buf[];
if(CopyBuffer(g_atrHandle, 0, 1, 1, buf) < 1)
return 0.0;
return buf[0];
}
//--- +1 buy bias, -1 sell bias, 0 no clear bias
int GetBias(const double atr)
{
double f[], s[];
if(CopyBuffer(g_fastHandle, 0, 1, 1, f) < 1)
return 0;
if(CopyBuffer(g_slowHandle, 0, 1, 1, s) < 1)
return 0;
double c = iClose(_Symbol, PERIOD_M1, 1);
if(c <= 0.0)
return 0;
if(MathAbs(f[0] - s[0]) < InpMinBiasAtr * atr)
return 0;
if(f[0] > s[0] && c > s[0])
return 1;
if(f[0] < s[0] && c < s[0])
return -1;
return 0;
}
//--- count own positions; type = -1 for all, else POSITION_TYPE_BUY / POSITION_TYPE_SELL
int CountOwn(const int type)
{
int cnt = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
if(PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
if(type >= 0 && PositionGetInteger(POSITION_TYPE) != type)
continue;
cnt++;
}
return cnt;
}
void CloseOwn(const int type)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
if(PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
if(type >= 0 && PositionGetInteger(POSITION_TYPE) != type)
continue;
trade.PositionClose(ticket);
}
}
void CloseAll()
{
CloseOwn(-1);
}
int TypeOfDir(const int dir)
{
return (dir == 1) ? (int)POSITION_TYPE_BUY : (int)POSITION_TYPE_SELL;
}
bool SessionOK()
{
if(!InpUseSessionFilter)
return true;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
int h = dt.hour;
if(InpSessionStartHour == InpSessionEndHour)
return true;
if(InpSessionStartHour < InpSessionEndHour)
return (h >= InpSessionStartHour && h < InpSessionEndHour);
return (h >= InpSessionStartHour || h < InpSessionEndHour);
}
bool NewsBlocked()
{
if(!InpUseNewsFilter)
return false;
datetime now = TimeCurrent();
if(g_lastNewsCheck != 0 && (now - g_lastNewsCheck) < 60)
return g_newsBlocked;
g_lastNewsCheck = now;
g_newsBlocked = false;
datetime from = now - (datetime)(InpNewsMinutesAfter * 60);
datetime to = now + (datetime)(InpNewsMinutesBefore * 60);
MqlCalendarValue values[];
int total = CalendarValueHistory(values, from, to, NULL, InpNewsCurrency);
if(total <= 0)
return false; // calendar unavailable (e.g. strategy tester) -> do not block
for(int i = 0; i < total; i++)
{
MqlCalendarEvent ev;
if(!CalendarEventById(values[i].event_id, ev))
continue;
if(ev.importance != CALENDAR_IMPORTANCE_HIGH)
continue;
g_newsBlocked = true;
break;
}
return g_newsBlocked;
}
void UpdateDayState()
{
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
double eq = AccountInfoDouble(ACCOUNT_EQUITY);
int dayKey = dt.year * 1000 + dt.day_of_year;
if(dayKey != g_lastDay)
{
g_lastDay = dayKey;
g_dayStartEquity = eq;
g_cyclesToday = 0;
g_dayHalted = false;
}
if(g_peakEquity <= 0.0)
g_peakEquity = eq;
if(eq > g_peakEquity)
g_peakEquity = eq;
long stamp = (long)TimeCurrent() / 60;
if(stamp != g_minuteStamp)
{
g_minuteStamp = stamp;
g_minuteCycles = 0;
}
}
bool RiskHaltTriggered()
{
if(g_dayHalted || g_ddHalted)
return true;
double eq = AccountInfoDouble(ACCOUNT_EQUITY);
if(InpMaxDailyLossPercent > 0.0 && g_dayStartEquity > 0.0)
{
double dayDD = (g_dayStartEquity - eq) / g_dayStartEquity * 100.0;
if(dayDD >= InpMaxDailyLossPercent)
{
g_dayHalted = true;
CloseAll();
Print("PROP GUARD: daily loss limit reached (", DoubleToString(dayDD, 2), "%). Halted for today.");
return true;
}
}
if(InpMaxTotalDDPercent > 0.0 && g_peakEquity > 0.0)
{
double totalDD = (g_peakEquity - eq) / g_peakEquity * 100.0;
if(totalDD >= InpMaxTotalDDPercent)
{
g_ddHalted = true;
CloseAll();
Print("PROP GUARD: max drawdown reached (", DoubleToString(totalDD, 2), "%). Halted until restart.");
return true;
}
}
return false;
}
bool EntryAllowed(const double atr)
{
if(g_dayHalted || g_ddHalted)
return false;
if(g_pauseUntil > 0 && TimeCurrent() < g_pauseUntil)
return false;
if(g_cyclesToday >= InpMaxCyclesPerDay)
return false;
if(InpMaxCyclesPerMinute > 0 && g_minuteCycles >= InpMaxCyclesPerMinute)
return false;
if(g_lastCycleEnd > 0 && (TimeCurrent() - g_lastCycleEnd) < InpCooldownSeconds)
return false;
if(!SessionOK())
return false;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(ask <= 0.0 || bid <= 0.0)
return false;
if((ask - bid) / g_point > InpMaxSpreadPoints)
return false;
double atrPts = atr / g_point;
if(atrPts < InpMinATRPoints || atrPts > InpMaxATRPoints)
return false;
if(NewsBlocked())
return false;
return true;
}
//--- lot per leg (fixed, or sized so the disaster stop across all legs costs ~risk%)
double CalcLotPerLeg(const double hardSLPoints)
{
double lot = InpFixedLot;
if(InpLotMode == LOT_PERCENT)
{
double riskMoney = AccountInfoDouble(ACCOUNT_EQUITY) * InpRiskPercent / 100.0;
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tickValue <= 0.0 || tickSize <= 0.0 || hardSLPoints <= 0.0)
return 0.0;
double moneyPerPointPerLot = tickValue * (g_point / tickSize);
double lossPerLot = hardSLPoints * moneyPerPointPerLot * InpLegsPerSide;
if(lossPerLot <= 0.0)
return 0.0;
lot = riskMoney / lossPerLot;
}
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
if(step <= 0.0)
step = 0.01;
lot = MathFloor(lot / step) * step;
if(lot < minLot)
lot = minLot;
lot = MathMin(lot, MathMin(maxLot, InpMaxLot));
int lotDigits = (step >= 1.0) ? 0 : (step >= 0.1 ? 1 : (step >= 0.01 ? 2 : 3));
return NormalizeDouble(lot, lotDigits);
}
//==================================================================
// CYCLE
//==================================================================
void OpenCycle(const double atr, const int dir)
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double stopLevel = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * g_point;
if(stopLevel <= 0.0)
stopLevel = 10.0 * g_point;
double tpBase = InpTPAtr * atr;
if(tpBase <= 0.0)
return;
//--- cost filter: the spread must be small versus the target
if((ask - bid) > InpMaxSpreadTPFrac * tpBase)
return;
double hardSL = MathMax(InpHardSLAtr * atr, stopLevel + 10.0 * g_point);
double lot = CalcLotPerLeg(hardSL / g_point);
if(lot <= 0.0)
return;
int legs = MathMax(1, MathMin(5, InpLegsPerSide));
int opened = 0;
for(int k = 1; k <= legs; k++)
{
double tpDist = MathMax(tpBase * (1.0 + (k - 1) * InpLegTPStep), stopLevel + 5.0 * g_point);
bool ok;
if(dir > 0)
ok = trade.Buy(lot, _Symbol, 0.0, NormalizePrice(ask - hardSL), NormalizePrice(ask + tpDist), InpTradeComment);
else
ok = trade.Sell(lot, _Symbol, 0.0, NormalizePrice(bid + hardSL), NormalizePrice(bid - tpDist), InpTradeComment);
if(ok)
opened++;
else
Print("Primary leg failed: ", trade.ResultRetcode(), " / ", trade.ResultRetcodeDescription());
}
if(opened == 0)
return;
g_phase = 1;
g_primaryDir = dir;
g_winnerDir = 0;
g_cycleStart = TimeCurrent();
g_hedgeTime = 0;
g_entry = (dir > 0) ? ask : bid;
g_hedgePrice = 0.0;
g_atrOpen = atr;
g_lot = lot;
g_cyclePnl = 0.0;
g_cyclesToday++;
g_minuteCycles++;
}
//--- open the opposite side with the same lots as the surviving primary legs
void HedgeNow()
{
int n = CountOwn(TypeOfDir(g_primaryDir));
if(n <= 0)
return;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double stopLevel = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * g_point;
if(stopLevel <= 0.0)
stopLevel = 10.0 * g_point;
double hardSL = MathMax(InpHardSLAtr * g_atrOpen, stopLevel + 10.0 * g_point);
int opened = 0;
for(int i = 0; i < n; i++)
{
bool ok;
if(g_primaryDir > 0) // primary is long -> hedge with shorts
ok = trade.Sell(g_lot, _Symbol, 0.0, NormalizePrice(bid + hardSL), 0.0, InpTradeComment);
else
ok = trade.Buy(g_lot, _Symbol, 0.0, NormalizePrice(ask - hardSL), 0.0, InpTradeComment);
if(ok)
opened++;
else
Print("Hedge leg failed: ", trade.ResultRetcode(), " / ", trade.ResultRetcodeDescription());
}
if(opened > 0)
{
g_phase = 2;
g_hedgePrice = (ask + bid) / 2.0;
g_hedgeTime = TimeCurrent();
}
}
void TrailSide(const int dir)
{
double stopLevel = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * g_point;
if(stopLevel <= 0.0)
stopLevel = 10.0 * g_point;
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double trailDist = InpTrailAtr * g_atrOpen;
double step = InpTrailStepAtr * g_atrOpen;
int type = TypeOfDir(dir);
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
if(PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
if(PositionGetInteger(POSITION_TYPE) != type)
continue;
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if(dir > 0)
{
double newSL = NormalizePrice(bid - trailDist);
if((sl <= 0.0 || newSL > sl + step) && newSL <= bid - stopLevel)
trade.PositionModify(ticket, newSL, tp);
}
else
{
double newSL = NormalizePrice(ask + trailDist);
if((sl <= 0.0 || newSL < sl - step) && newSL >= ask + stopLevel)
trade.PositionModify(ticket, newSL, tp);
}
}
}
void FinalizeCycle()
{
if(g_cyclePnl > 0.0)
{
g_wins++;
g_grossWin += g_cyclePnl;
g_consecLosses = 0;
}
else
{
g_losses++;
g_grossLoss += -g_cyclePnl;
g_consecLosses++;
}
g_phase = 0;
g_primaryDir = 0;
g_winnerDir = 0;
g_lastCycleEnd = TimeCurrent();
int n = g_wins + g_losses;
if(n > 0 && (n % 25) == 0)
{
double pf = (g_grossLoss > 0.0) ? g_grossWin / g_grossLoss : 0.0;
Print("STATS after ", n, " cycles | win rate ", DoubleToString(100.0 * g_wins / n, 1),
"% | profit factor ", DoubleToString(pf, 2),
" | net ", DoubleToString(g_grossWin - g_grossLoss, 2));
}
if(InpMaxConsecLosses > 0 && g_consecLosses >= InpMaxConsecLosses)
{
g_pauseUntil = TimeCurrent() + (datetime)(InpPauseMinutes * 60);
g_consecLosses = 0;
Print("LOSS STREAK GUARD: pausing new cycles for ", InpPauseMinutes, " minutes.");
}
}
void ManageCycle()
{
int total = CountOwn(-1);
//--- cycle finished (every leg closed by TP / SL / us)
if(g_phase != 0 && total == 0)
{
FinalizeCycle();
return;
}
//--- adopt orphan positions (e.g. EA restarted mid-cycle)
if(g_phase == 0 && total > 0)
{
int nb = CountOwn(POSITION_TYPE_BUY);
int ns = CountOwn(POSITION_TYPE_SELL);
double atr = GetATR();
double mid = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) + SymbolInfoDouble(_Symbol, SYMBOL_BID)) / 2.0;
g_primaryDir = (nb >= ns) ? 1 : -1;
g_phase = (nb > 0 && ns > 0) ? 2 : 1;
g_cycleStart = TimeCurrent();
g_hedgeTime = TimeCurrent();
g_entry = mid;
g_hedgePrice = mid;
g_atrOpen = (atr > 0.0) ? atr : 1.0;
g_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
g_cyclePnl = 0.0;
}
if(g_phase == 0)
return;
datetime now = TimeCurrent();
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double mid = (ask + bid) / 2.0;
//--- PHASE 1: primary only, waiting for TP or the delayed hedge
if(g_phase == 1)
{
if((now - g_cycleStart) >= InpHedgeDelaySeconds)
{
double adverse = (g_primaryDir > 0) ? (g_entry - bid) : (ask - g_entry);
bool want = InpHedgeRequireAdverse ? (adverse >= InpHedgeTriggerAtr * g_atrOpen) : true;
if(want)
HedgeNow();
}
if(g_phase == 1 && (now - g_cycleStart) >= InpMaxPrimarySeconds)
CloseAll();
return;
}
//--- PHASE 2: locked, wait for a release
if(g_phase == 2)
{
double rel = InpReleaseAtr * g_atrOpen;
double fromHedge = (g_primaryDir > 0) ? (mid - g_hedgePrice) : (g_hedgePrice - mid); // >0 = recovery
if(fromHedge >= rel)
{
CloseOwn(TypeOfDir(-g_primaryDir)); // price recovered: drop the hedge, primary runs to its TP
g_winnerDir = g_primaryDir;
g_phase = 3;
}
else if(fromHedge <= -rel)
{
CloseOwn(TypeOfDir(g_primaryDir)); // price keeps going against primary: keep the hedge side
g_winnerDir = -g_primaryDir;
g_phase = 3;
}
else if((now - g_hedgeTime) >= InpLockMaxSeconds)
{
CloseAll(); // no resolution: flatten the lock
}
return;
}
//--- PHASE 3: one side left, trail it
if(g_phase == 3)
{
TrailSide(g_winnerDir);
if((now - g_cycleStart) >= InpMaxHoldSeconds)
CloseAll();
}
}
void UpdateStatusPanel()
{
static datetime lastPaint = 0;
datetime now = TimeCurrent();
if(now == lastPaint)
return;
lastPaint = now;
int n = g_wins + g_losses;
double wr = (n > 0) ? 100.0 * g_wins / n : 0.0;
double pf = (g_grossLoss > 0.0) ? g_grossWin / g_grossLoss : 0.0;
double spreadPts = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / g_point;
string ph = (g_phase == 0) ? "IDLE" : (g_phase == 1 ? "PRIMARY" : (g_phase == 2 ? "LOCKED" : "RELEASED"));
if(g_dayHalted || g_ddHalted)
ph = "HALTED";
Comment(StringFormat("HORIZON HEDGE SCALPER V2 | %s | spread %.0f | cycles %d (today %d)\nwin rate %.1f%% | profit factor %.2f | net %.2f",
ph, spreadPts, n, g_cyclesToday, wr, pf, g_grossWin - g_grossLoss));
}
//==================================================================
// EVENT HANDLERS
//==================================================================
int OnInit()
{
if(!IsValidSymbol())
{
Print("HORIZON AI BOT HEDGE SCALPER V2 trades XAUUSD / GOLD only. Current symbol: ", _Symbol);
return INIT_FAILED;
}
if((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE) != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
{
Print("This EA needs a HEDGING account (buys and sells held together). Netting accounts are not supported.");
return INIT_FAILED;
}
g_point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
g_digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
if(g_point <= 0.0)
return INIT_FAILED;
g_atrHandle = iATR(_Symbol, PERIOD_M1, InpATRPeriod);
g_fastHandle = iMA(_Symbol, PERIOD_M1, InpFastEMA, 0, MODE_EMA, PRICE_CLOSE);
g_slowHandle = iMA(_Symbol, PERIOD_M1, InpSlowEMA, 0, MODE_EMA, PRICE_CLOSE);
if(g_atrHandle == INVALID_HANDLE || g_fastHandle == INVALID_HANDLE || g_slowHandle == INVALID_HANDLE)
{
Print("Failed to create indicator handles.");
return INIT_FAILED;
}
trade.SetExpertMagicNumber((ulong)InpMagic);
trade.SetDeviationInPoints((ulong)InpSlippagePoints);
trade.SetTypeFillingBySymbol(_Symbol);
trade.SetAsyncMode(false);
trade.LogLevel(LOG_LEVEL_ERRORS);
g_lastDay = -1;
g_dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
g_peakEquity = g_dayStartEquity;
g_phase = 0;
g_cyclesToday = 0;
g_minuteStamp = -1;
g_minuteCycles = 0;
g_dayHalted = false;
g_ddHalted = false;
g_consecLosses = 0;
g_pauseUntil = 0;
g_lastCycleEnd = 0;
g_lastNewsCheck = 0;
g_newsBlocked = false;
g_wins = 0; g_losses = 0; g_grossWin = 0.0; g_grossLoss = 0.0;
Print("HORIZON AI BOT HEDGE SCALPER V2 initialised on ", _Symbol,
" | legs/side=", InpLegsPerSide, " | hedge delay=", InpHedgeDelaySeconds, "s");
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");
if(g_atrHandle != INVALID_HANDLE)
IndicatorRelease(g_atrHandle);
if(g_fastHandle != INVALID_HANDLE)
IndicatorRelease(g_fastHandle);
if(g_slowHandle != INVALID_HANDLE)
IndicatorRelease(g_slowHandle);
g_atrHandle = g_fastHandle = g_slowHandle = INVALID_HANDLE;
}
//+------------------------------------------------------------------+
void OnTick()
{
UpdateDayState();
if(RiskHaltTriggered())
return;
ManageCycle();
UpdateStatusPanel();
if(g_phase != 0 || CountOwn(-1) > 0)
return;
double atr = GetATR();
if(atr <= 0.0)
return;
if(!EntryAllowed(atr))
return;
int dir = GetBias(atr);
if(dir == 0)
return;
OpenCycle(atr, dir);
}
//+------------------------------------------------------------------+
// Track realised P/L of the current cycle (profit + swap + commission)
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
if(trans.type != TRADE_TRANSACTION_DEAL_ADD)
return;
if(trans.symbol != _Symbol)
return;
if(!HistoryDealSelect(trans.deal))
return;
if(HistoryDealGetInteger(trans.deal, DEAL_MAGIC) != InpMagic)
return;
g_cyclePnl += HistoryDealGetDouble(trans.deal, DEAL_PROFIT)
+ HistoryDealGetDouble(trans.deal, DEAL_SWAP)
+ HistoryDealGetDouble(trans.deal, DEAL_COMMISSION);
}
//+------------------------------------------------------------------+