View source
#property strict
#property version "1.00"
const ulong LockedMagic=105888993595833;
const string LockedAnchor="ETHUSD";
string LegNames[]={"ETHUSD"};
double LegWeights[]={1.0};
string DSUniverse[];
string MapNames[]={"BTCUSD","ETHUSD","SOLUSD"};
string MapSymbols[]={"BTCUSD","ETHUSD","SOLUSD"};
datetime MapFirstH1[]={1388613600,1462140000,1615471200};
datetime DSFirstH1(const string broker) { for(int j=0;j<ArraySize(MapSymbols);j++) if(MapSymbols[j]==broker) return MapFirstH1[j]; return 0; }
string DSBrokerSymbol(const string canonical);
// USD-quoted crypto H4/D1 signals. Targets use only completed native bars.
#ifndef DS_CRYPTO_SIGNALS
#define DS_CRYPTO_SIGNALS
struct CryptoCache
{
string key;
datetime cut;
int signedState;
int target;
};
CryptoCache cryptoStates[];
int CryptoSign(const double a){ return a>0?1:(a<0?-1:0); }
bool CryptoTarget(const string rule,const string sym,const ENUM_TIMEFRAMES frame,const datetime hour,int &side)
{
if(frame!=PERIOD_D1 && frame!=PERIOD_H4) return false;
const int seconds=PeriodSeconds(frame);
const datetime cut=(datetime)(((long)hour/seconds)*seconds);
const string key=rule+"|"+sym+"|"+IntegerToString((int)frame);
int slot=-1;
for(int i=0;i<ArraySize(cryptoStates);i++) if(cryptoStates[i].key==key) { slot=i; break; }
if(slot<0)
{
slot=ArraySize(cryptoStates);
if(ArrayResize(cryptoStates,slot+1)!=slot+1) return false;
cryptoStates[slot].key=key; cryptoStates[slot].cut=0;
cryptoStates[slot].signedState=0; cryptoStates[slot].target=0;
}
if(cryptoStates[slot].cut==cut) { side=cryptoStates[slot].target; return true; }
string fields[];
const int count=StringSplit(rule,'_',fields);
if(count<4 || fields[0]!="coin" || (fields[count-1]!="ls" && fields[count-1]!="lc")) return false;
const int a=(int)StringToInteger(fields[2]);
const int b=count==5?(int)StringToInteger(fields[3]):0;
if(a<=0) return false;
const datetime start=DSFirstH1(sym);
if(start<=0) return false;
const datetime firstBucket=(datetime)(((long)start/seconds)*seconds);
MqlRates bars[];
int n=0;
int value=0;
if(cut>firstBucket && fields[1]=="ch")
{
if(b<=0 || b>a) return false;
datetime since=firstBucket;
if(cryptoStates[slot].cut>0 && cryptoStates[slot].cut<=cut)
{
const int idx=iBarShift(sym,frame,cryptoStates[slot].cut,false);
if(idx<0) return false;
const datetime history=iTime(sym,frame,idx+a);
since=history>firstBucket?history:firstBucket;
value=cryptoStates[slot].signedState;
}
n=CopyRates(sym,frame,since,cut-1,bars);
if(n<0) return false;
for(int i=a;i<n;i++)
{
if(bars[i].time<cryptoStates[slot].cut) continue;
double high=bars[i-1].high,low=bars[i-1].low,exitHi=high,exitLo=low;
for(int j=1;j<=a;j++)
{
high=MathMax(high,bars[i-j].high); low=MathMin(low,bars[i-j].low);
if(j<=b){exitHi=MathMax(exitHi,bars[i-j].high);exitLo=MathMin(exitLo,bars[i-j].low);}
}
const double close=bars[i].close;
if((value>0 && close<exitLo) || (value<0 && close>exitHi)) value=0;
if(close>high)value=1;
if(close<low)value=-1;
}
}
else if(cut>firstBucket)
{
const int need=fields[1]=="mom"?a+1:(fields[1]=="sma"?b:a);
if(need<=0) return false;
n=CopyRates(sym,frame,cut-1,need,bars);
if(n<0) return false;
if(n>=need && bars[n-need].time>=firstBucket)
{
const double close=bars[n-1].close;
if(fields[1]=="mom") value=CryptoSign(close-bars[n-1-a].close);
else if(fields[1]=="sma")
{
if(a>b) return false;
double fast=0,slow=0;
for(int i=0;i<b;i++){slow+=bars[n-1-i].close;if(i<a)fast+=bars[n-1-i].close;}
value=CryptoSign(fast/a-slow/b);
}
else if(fields[1]=="zrev")
{
double mu=0,var=0;
for(int i=0;i<a;i++)mu+=MathLog(bars[n-1-i].close)/a;
for(int i=0;i<a;i++){const double delta=MathLog(bars[n-1-i].close)-mu;var+=delta*delta/a;}
if(var>0){const double z=(MathLog(close)-mu)/MathSqrt(var);value=z>b?-1:(z< -b?1:0);}
}
else return false;
}
}
cryptoStates[slot].cut=cut;
cryptoStates[slot].signedState=value;
side=(fields[count-1]=="lc" && value<0)?0:value;
cryptoStates[slot].target=side;
return true;
}
#endif
double Component0[]={1.0};
bool SelectedWeight(const int leg,const string sym,const datetime hour,double &weight)
{
weight=0;
int side=0;
if(Component0[leg]>0)
{
side=0;
if(!CryptoTarget("coin_ch_80_40_lc",sym,PERIOD_H4,hour,side) || side< -1 || side>1) return false;
weight+=side*Component0[leg];
}
return true;
}
// Shared MT5 execution for explicitly frozen, per-symbol H1-opening targets.
// The assembler declares LegNames, the maximum LegWeights, the
// broker symbol map, default exposure, and the SelectedWeight() callback.
#include <Trade/Trade.mqh>
input bool TesterOnly = true;
input ulong EquityLogId = 0; // Unique tag for the tester's monthly equity file.
input double Exposure = 0.2;
CTrade dsTrade;
string dsSymbols[];
bool dsDone[],dsReady[];
int dsSides[];
double dsVolumes[];
datetime dsHour=0, dsWake=0;
double dsOpeningEquity=0;
bool dsFinished=false;
uint dsErrors=0;
int dsMonthlyFile=INVALID_HANDLE;
datetime dsMonthStart=0,dsNextMonth=0,dsLastTick=0,dsFirstMonthTick=0;
double dsLastMarkedEquity=0,dsLastMarkedBalance=0;
void DSWriteMonth(const bool finalRow,const double ending)
{
if(dsMonthlyFile==INVALID_HANDLE || dsLastTick<=0) return;
FileWrite(dsMonthlyFile,TimeToString(dsMonthStart,TIME_DATE),TimeToString(dsFirstMonthTick,TIME_DATE|TIME_SECONDS),
TimeToString(dsLastTick,TIME_DATE|TIME_SECONDS),DoubleToString(dsLastMarkedEquity,2),
DoubleToString(dsLastMarkedBalance,2),finalRow?DoubleToString(ending,2):"");
FileFlush(dsMonthlyFile);
PrintFormat("Research tester monthly equity %s %.2f",TimeToString(dsMonthStart,TIME_DATE),dsLastMarkedEquity);
}
void DSObserveMonth(const datetime now)
{
if(dsMonthlyFile==INVALID_HANDLE) return;
if(now>=dsNextMonth)
{
DSWriteMonth(false,0);
MqlDateTime t;
if(!TimeToStruct(now,t)) return;
t.day=1; t.hour=0; t.min=0; t.sec=0;
dsMonthStart=StructToTime(t); dsFirstMonthTick=now;
if(t.mon==12) { t.year++; t.mon=1; } else t.mon++;
dsNextMonth=StructToTime(t);
}
dsLastTick=now;
dsLastMarkedEquity=AccountInfoDouble(ACCOUNT_EQUITY);
dsLastMarkedBalance=AccountInfoDouble(ACCOUNT_BALANCE);
}
string DSBrokerSymbol(const string canonical)
{
for(int i=0;i<ArraySize(MapNames);i++)
if(MapNames[i]==canonical) return MapSymbols[i];
return "";
}
bool DSAllowed(const string canonical)
{
if(canonical=="BTCUSD" || canonical=="SOLUSD" || canonical=="ETHUSD") return true;
if(StringLen(canonical)!=6) return false;
const string base=StringSubstr(canonical,0,3), quote=StringSubstr(canonical,3);
const string fx="|USD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|";
return base!=quote && StringFind(fx,"|"+base+"|")>=0 && StringFind(fx,"|"+quote+"|")>=0;
}
bool DSSized(const string sym,const int side,const MqlTick &tick,const double allocation,double &lots)
{
lots=0;
if(side==0) return true;
const double price=(tick.bid+tick.ask)/2;
const double contract=SymbolInfoDouble(sym,SYMBOL_TRADE_CONTRACT_SIZE);
const double step=SymbolInfoDouble(sym,SYMBOL_VOLUME_STEP);
if(price<=0 || contract<=0 || step<=0 || dsOpeningEquity<=0) return false;
const string account=AccountInfoString(ACCOUNT_CURRENCY);
const string base=SymbolInfoString(sym,SYMBOL_CURRENCY_BASE);
const string quote=SymbolInfoString(sym,SYMBOL_CURRENCY_PROFIT);
double notional=contract;
if(base!=account)
{
if(quote==account) notional=contract*price;
else
{
double move=0;
if(!OrderCalcProfit(ORDER_TYPE_BUY,sym,1.0,price,price*1.01,move) || move<=0) return false;
notional=move*100;
}
}
double raw=dsOpeningEquity*Exposure*allocation/notional;
const double bound=SymbolInfoDouble(sym,SYMBOL_VOLUME_LIMIT);
if(bound>0) raw=MathMin(raw,bound);
lots=NormalizeDouble(MathFloor(raw/step+1e-10)*step,8);
if(lots<SymbolInfoDouble(sym,SYMBOL_VOLUME_MIN)) lots=0;
return true;
}
bool DSFilled(const bool sent,const string symbol)
{
const uint rc=dsTrade.ResultRetcode();
if(sent && (rc==TRADE_RETCODE_DONE || rc==TRADE_RETCODE_DONE_PARTIAL)) return true;
dsErrors++;
if(dsErrors<=8 || dsErrors%500==0)
PrintFormat("Research execution %s: %u %s (events %u)",symbol,rc,dsTrade.ResultRetcodeDescription(),dsErrors);
return false;
}
bool DSAlign(const string sym,int side,const double lots)
{
// Return true only after actual position volume has been confirmed.
if(lots==0) side=0;
const bool hedge=AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
double owned=0;
ulong reduceTicket=0;
double reduceLots=0;
if(!dsTrade.SetTypeFillingBySymbol(sym)) return false;
for(int i=PositionsTotal()-1;i>=0;i--)
{
const ulong ticket=PositionGetTicket(i);
if(ticket==0 || PositionGetString(POSITION_SYMBOL)!=sym) continue;
if((ulong)PositionGetInteger(POSITION_MAGIC)!=LockedMagic)
{
if(!hedge) return true; // Shared net position cannot be attributed safely.
continue;
}
const int held=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY?1:-1;
const double v=PositionGetDouble(POSITION_VOLUME);
if(held!=side)
{
DSFilled(dsTrade.PositionClose(ticket),sym);
return false;
}
owned+=v;
if(v>reduceLots) { reduceTicket=ticket; reduceLots=v; }
}
const double step=SymbolInfoDouble(sym,SYMBOL_VOLUME_STEP);
const double maximum=SymbolInfoDouble(sym,SYMBOL_VOLUME_MAX);
const double minimum=SymbolInfoDouble(sym,SYMBOL_VOLUME_MIN);
if(step<=0 || maximum<=0 || minimum<=0) return false;
const double diff=NormalizeDouble(lots-owned,8);
if(MathAbs(diff)<minimum-step*0.01) return true;
double qty=MathMin(MathAbs(diff),maximum);
qty=NormalizeDouble(MathFloor(qty/step+1e-8)*step,8);
if(qty<minimum) return true;
if(hedge && diff<0)
{
if(qty>=reduceLots-step*0.01)
DSFilled(dsTrade.PositionClose(reduceTicket),sym);
else
DSFilled(dsTrade.PositionClosePartial(reduceTicket,qty),sym);
return false;
}
const bool buy=(side>0)==(diff>0);
DSFilled(buy?dsTrade.Buy(qty,sym):dsTrade.Sell(qty,sym),sym);
return false;
}
int OnInit()
{
if((TesterOnly && !MQLInfoInteger(MQL_TESTER)) || Exposure<=0 || !MathIsValidNumber(Exposure)) return INIT_PARAMETERS_INCORRECT;
const int n=ArraySize(LegNames);
if(n==0 || n!=ArraySize(LegWeights) || ArraySize(MapNames)!=ArraySize(MapSymbols)) return INIT_PARAMETERS_INCORRECT;
ArrayResize(dsSymbols,n); ArrayResize(dsDone,n); ArrayResize(dsReady,n);
ArrayResize(dsSides,n); ArrayResize(dsVolumes,n);
double total=0;
for(int i=0;i<n;i++)
{
dsSymbols[i]=DSBrokerSymbol(LegNames[i]);
if(!DSAllowed(LegNames[i]) || dsSymbols[i]=="" || LegWeights[i]<=0 || !SymbolSelect(dsSymbols[i],true)) return INIT_PARAMETERS_INCORRECT;
total+=LegWeights[i];
}
if(total<=0 || _Symbol!=LockedAnchor) return INIT_PARAMETERS_INCORRECT;
if(MQLInfoInteger(MQL_TESTER) && EquityLogId>0)
{
const string fn="StrategyResearch\\monthly-"+IntegerToString((long)EquityLogId)+".csv";
dsMonthlyFile=FileOpen(fn,FILE_WRITE|FILE_CSV|FILE_ANSI|FILE_COMMON,',');
if(dsMonthlyFile==INVALID_HANDLE) { PrintFormat("Research tester monthly file error %d",GetLastError()); return INIT_FAILED; }
FileWrite(dsMonthlyFile,"month","first_tick","last_tick","marked_equity","marked_balance","final_tester_equity");
}
dsTrade.SetExpertMagicNumber(LockedMagic);
dsTrade.SetAsyncMode(false);
return INIT_SUCCEEDED;
}
void OnTick()
{
const datetime now=TimeCurrent();
DSObserveMonth(now);
const datetime hour=(datetime)(((long)now/3600)*3600);
if(hour!=dsHour)
{
dsHour=hour;
dsWake=0;
dsFinished=false;
dsOpeningEquity=AccountInfoDouble(ACCOUNT_EQUITY);
ArrayInitialize(dsDone,false);
ArrayInitialize(dsReady,false);
}
if(dsFinished || now<dsWake) return;
bool all=true;
for(int i=0;i<ArraySize(dsSymbols);i++)
{
if(dsDone[i]) continue;
MqlTick tick;
const string sym=dsSymbols[i];
if(!SymbolInfoTick(sym,tick) || tick.time<hour || tick.time>now || tick.bid<=0 ||
tick.ask<tick.bid || iTime(sym,PERIOD_H1,0)!=hour) { all=false; continue; }
if(!dsReady[i])
{
double weight=0;
if(!SelectedWeight(i,sym,hour,weight) || !MathIsValidNumber(weight) ||
MathAbs(weight)>LegWeights[i]+1e-8) { all=false; continue; }
const int side=weight>0?1:(weight<0?-1:0);
if(!DSSized(sym,side,tick,MathAbs(weight),dsVolumes[i])) { all=false; continue; }
dsSides[i]=side;
dsReady[i]=true;
}
dsDone[i]=DSAlign(sym,dsSides[i],dsVolumes[i]);
if(!dsDone[i]) all=false;
}
if(dsMonthlyFile!=INVALID_HANDLE)
{
dsLastMarkedEquity=AccountInfoDouble(ACCOUNT_EQUITY);
dsLastMarkedBalance=AccountInfoDouble(ACCOUNT_BALANCE);
}
dsFinished=all;
dsWake=now+(now-hour<30?1:30);
}
double OnTester()
{
const double ending=TesterStatistics(STAT_INITIAL_DEPOSIT)+TesterStatistics(STAT_PROFIT);
DSWriteMonth(true,ending);
return ending;
}
void OnDeinit(const int reason)
{
if(dsMonthlyFile!=INVALID_HANDLE) FileClose(dsMonthlyFile);
PrintFormat("Research execution ended, trade error responses=%u.",dsErrors);
}