System Logic Overview
This automated trading script is designed to manage currency and commodity positions by identifying specific price boundaries and executing trades based on "channel" logic. It primarily operates on the principle of reacting to price extremes while incorporating dynamic risk management and automatic position scaling.
Dynamic Risk and Account Management
The script begins by evaluating the user's account balance to determine the appropriate trade size. It features a tiered calculation system:
- It adjusts the number of lots traded based on whether the account balance is above or below specific thresholds (e.g., $1,000 or $10,000).
- It ensures that the trade volume remains proportional to the account size while capping the multiplier to maintain safety.
- The script identifies the specific financial instrument being traded (such as EURUSD, GBPUSD, etc.) to handle naming and data logging correctly.
Price Boundary Analysis
A core component of the logic is the determination of "High" and "Low" price points.
- Range Calculation: The script monitors price action to establish significant highs and lows. During specific late-session times, it captures the highest and lowest prices to define a trading range.
- Trend Indicators: It utilizes a "ZigZag" technical indicator to identify structural turns in the market. This helps the system distinguish between a continuing trend and a potential reversal point, influencing whether it favors "Buy" or "Sell" opportunities.
Trade Execution Strategy
The script focuses on placing "Stop" orders, which are triggered only when the price moves in a specific direction.
- Entry Logic: Instead of entering trades immediately, it places pending orders at set distances from the identified High and Low boundaries.
- Auto vs. Manual Mode: The system includes a toggle that determines how aggressively it seeks these entries. In automatic mode, it looks for specific price gaps relative to the established range to confirm a valid entry point.
- Position Management: It monitors the total number of active trades and pending orders, ensuring it doesn't over-leverage the account by opening too many simultaneous positions.
Active Trade Management and Protection
Once a trade is active, the script performs several automated maintenance tasks:
- Break-Even Logic: If a trade reaches a specific profit milestone, the script can automatically move the "Stop Loss" to the entry price. This secures the trade so that it cannot result in a net loss if the market reverses.
- Dynamic Trailing: The script calculates distances from the current price to the range boundaries. If the price moves favorably, it adjusts the Stop Loss levels dynamically to "lock in" profit as the trend progresses.
- Profit Tracking: It tracks the cumulative profit of all open positions and logs this data into a file for historical review.
Session Cleanup and Housekeeping
To ensure the system remains organized, it performs daily "housekeeping" tasks:
- Timed Closures: At a specific time of day (late evening), the script automatically closes all active positions and tallies the final profit for the session.
- Order Purging: It identifies and deletes any leftover pending orders that were not triggered, clearing the workspace for the next trading session.
- Data Display: Throughout operation, the script provides a real-time dashboard on the chart screen, showing the current time, active position counts, total profits, and indicator values.
/*[[
Name := Pipsoed
Author := Copyright © 2005, HomeSoft Corp.
Link := spiky@sinet.spb.ru
Lots := 0.1
Stop Loss := 1000
Take Profit := 1000
Trailing Stop := 0
]]*/
extern int
mgod=2005;
extern bool
auto=true;
extern double
lots=0.1;
extern int
del=9,
tpl=120,
stl=30,
depth=12,
deviation=5,
backstep=3,
nstl=1,
eaID=993872;
int
cnt,
j,
s,b,
os,ob,
mods,
top,
oldf,
LTT,
dblok;
string
reg,
fname;
double
MaxH,MinL,
bsum,ssum,
mlot,
summa,
MidL,
kr,
blot,
slot,
ks,
kb,
ps,
pb,
DSum,
zz,
zz0;
int start()
{
Preset();
RangeCalculation();
OrderManagement();
DataDisplay();
ModifyOrder();
ModifyOrder2();
CloseOrder();
DeleteOrder();
PlaceOrder();
return;
}
//----------------------------------------Âû÷èñëåíèå äàííûõ äëÿ ðàáîòû ýêñïåðà-------------------------------------
void Preset()
{
//if (start==0 ) return;
if (Year()<mgod ) return;
if (lots>=1 && AccountBalance()>=10000 ) kr=NormalizeDouble((AccountBalance()/10000),0);
if (lots==1 && AccountBalance()<10000 ) kr=1;
if (lots<1 && AccountBalance()>=1000 ) kr=NormalizeDouble((AccountBalance()/1000),0);
if (lots<1 && AccountBalance()<1000 ) kr=1;
if (kr>1000 ) kr=1000;
mlot=kr*lots;
if (mlot>1 ) mlot=NormalizeDouble((kr*lots),0);
j++;
if (Minute()==0 ) j=0;
if (Symbol()=="EURUSD" ) fname="FEUR";
if (Symbol()=="GBPUSD" ) fname="FGBP";
if (Symbol()=="USDCHF" ) fname="FCHF";
if (Symbol()=="USDJPY" ) fname="FJPY";
if (Symbol()=="USDCAD" ) fname="FCAD";
if (Hour()>=0 && Minute()>=0 && j==5 && s+b==0 )
{
oldf=FileOpen(fname,FILE_CSV|FILE_WRITE,"!");
FileSeek(oldf,0,SEEK_END);
FileWrite(oldf,Month(),Day(),DSum);
FileClose(oldf);
DSum=0;
}
if (auto) reg="Àâòî";
if (!auto) reg="Õýíäë";
}
void RangeCalculation()
{
if (((High[0]-Low[0])/Point)>=10 && Hour()==23 && Minute()>=55 )
{
MaxH = High[0];
MinL = Low[0];
} else {
MaxH = High[1];
MinL = Low[1];
}
MidL = NormalizeDouble(((MaxH+MinL)/2),Digits);
zz=iCustom(Symbol(),0,"ZigZag",depth,deviation,backstep,0,3);
zz0=iCustom(Symbol(),0,"ZigZag",depth,deviation,backstep,0,0);
if (zz!=0 && zz>High[0] && Hour()==23 && Minute()>=55 ) top=1;
if (zz!=0 && zz<Low[0] && Hour()==23 && Minute()>=55 ) top=-1;
if (zz0>0 ) top=0;
}
//----------------------------------------Ïîäñ÷¸ò àêòèâíûõ è ïàññèâíûõ îðäåðîâ----------------------------------------
void OrderManagement()
{
s=0; b=0;
os=0; ob=0;
summa=0;
slot=0;blot=0;
ssum=0;bsum=0;
for (int cnt=0; cnt<OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()==eaID && OrderSymbol()==Symbol())
{
if ( OrderType()==OP_SELL || OrderType()==OP_BUY)
summa=summa+OrderProfit();
if ( OrderType()==OP_SELL )
{
ssum=ssum+OrderProfit();
slot=slot+OrderLots();
s++;
}
if ( OrderType()==OP_BUY )
{
bsum=bsum+OrderProfit();
blot=blot+OrderLots();
b++;
}
if ( OrderType()==OP_SELLSTOP ) os++;
if ( OrderType()==OP_BUYSTOP ) ob++;
}
}
if (s+b==0)
{
ps=0; pb=0;
ks=0; kb=0;
mods=0;
}
}
//---------------------------------------------------Êîììåíòàðèè------------------------------------------------------
void DataDisplay()
{
Comment("Data: ",Year(),".",Month(),".",Day()," Time ",Hour(),":",Minute()," JInd=",j," APoz=",s+b," Ords=",os+ob," Ks=",ks,
" Kb=",kb," Ps=",ps," Pb=",pb," SumProf=",MathRound(DSum)," Ðåæèì: ",reg);
Print("Data: ",Year(),".",Month(),".",Day()," Time ",Hour(),":",Minute()," JInd=",j," Ords=",os+ob," APoz=",s+b," Ks=",ks,
" Kb=",kb," Mlot=",mlot," ZZ0=",MathRound(zz0)," ZZ3=",MathRound(zz)," SumProf=",MathRound(DSum)," Profit=",MathRound(summa));
if (CurTime()-LTT<15 ) return;
}
//------------------------------Ïðîöåäóðà ïåðåâîäà ïðîôèòíîé ïîçèöèè â áåçúóáûòîê-------------------------------------
void ModifyOrder()
{
if (summa>=100*mlot && mods==0 )
{
for (int cnt=0; cnt<OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()==eaID && OrderSymbol()==Symbol())
{
if ( OrderType()==OP_SELL && s>0 && (OrderOpenPrice()-Close[0])/Point>=10 )
{
OrderModify(OrderTicket(),OrderOpenPrice(),
OrderOpenPrice()-nstl*Point,OrderTakeProfit(),Gold);
mods=1;
return;
}
if ( OrderType()==OP_BUY && b>0 && (Close[0]-OrderOpenPrice())/Point>=10 )
{
OrderModify(OrderTicket(),OrderOpenPrice(),
OrderOpenPrice()+nstl*Point,OrderTakeProfit(),Gold);
mods=1;
return;
}
}
}
}
}
//--------------------------------Ïðîöåäóðà ìîäèôèêàöèè ñòîïà ïðîôèòíîé ïîçèöèè--------------------------------------
void ModifyOrder2()
{
ks=NormalizeDouble((((MinL-Close[0])/Point)/stl),0);
kb=NormalizeDouble((((Close[0]-MaxH)/Point)/stl),0);
if (ks<0) ks=0; if (kb<0) kb=0;
if (summa>0 && (ks>=1 || kb>=1) && (ks>ps || kb>pb))
{
for (int cnt=0; cnt<OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()==eaID && OrderSymbol()==Symbol())
{
if ( OrderType()==OP_SELL && s>0 && Close[0]-OrderOpenPrice()>=6)
{
OrderModify(OrderTicket(),OrderOpenPrice(),
OrderOpenPrice()-ks*stl*Point+stl*Point,
OrderTakeProfit(),Gold);
ps=ks;
return;
}
if ( OrderType()==OP_BUY && b>0 && OrderOpenPrice()-Close[0]>=6)
{
OrderModify(OrderTicket(),OrderOpenPrice(),
OrderOpenPrice()+kb*stl*Point-stl*Point,
OrderTakeProfit(),Gold);
pb=kb;
return;
}
}
}
}
}
//-------------------------------------------Çàêðûòèå àêòèâíûõ ïîçèöèé ----------------------------------------------
void CloseOrder()
{
if (Hour()==23 && Minute()>=50 && s+b>0 )
{
for (int cnt=0; cnt<OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()==eaID && OrderSymbol()==Symbol())
{
if (OrderType()==OP_SELL)
{
DSum=DSum+OrderProfit();
OrderClose(OrderTicket(),OrderLots(),Ask,5,Red);
return;
}
if (OrderType()==OP_BUY)
{
DSum=DSum+OrderProfit();
OrderClose(OrderTicket(),OrderLots(),Bid,5,Red);
return;
}
}
}
}
}
//-----------------------------------------Óäàëåíèå íåèñïîëüçîâàííûõ îäåðîâ-------------------------------------------
void DeleteOrder()
{
if (Hour()==23 && Minute()<50) dblok=0;
if (Hour()==23 && Minute()>=50 && dblok==0)
{
if (os+ob==1) dblok=1;
for (int cnt=0; cnt<OrdersTotal(); cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()==eaID && OrderSymbol()==Symbol())
{
OrderDelete(OrderTicket());
return;
}
}
}
}
//------------------------------------------Âûñòàâëåíèå êàíàëüíûõ îðäåðîâ---------------------------------------------
void PlaceOrder()
{
if ((Hour()==23 && Minute()>=55) || s+b+os+ob<2 )
{
if (auto==0 )
Comment("ÓÑÒÀÍÎÂÈÒÅ ÄÂÀ ÎÐÄÅÐÀ ÇÀ ÏÐÅÄÅËÀÌÈ ÊÀÍÀËÀ (Â ÐÅÆÈÌÅ ÀÂÒÎ ÝÒÎÃÎ ÄÅËÀÒÜ ÍÅ ÍÀÄÎ), À ÎÑÒÀËÜÍÎÅ ÑÄÅËÀÞ ß");
if (auto==1 && MaxH!=0 && MinL!=0 )
{
if (os==0 && s==0 && ((Close[0]-MinL)/Point)>=5 && (top==1 || top==0))
{
OrderSend(Symbol(),OP_SELLSTOP,mlot,
MinL-del*Point,5,MinL-del*Point+stl*Point,MinL-del*Point-tpl*Point,
NULL,eaID,0,Gold);
return;
}
if (os==0 && s==0 && ((Close[0]-MinL)/Point)<=0 && (top==1 || top==0))
{
OrderSend(Symbol(),OP_SELLSTOP,mlot,
Bid-del*Point,5,Bid-del*Point+stl*Point,Bid-del*Point-tpl*Point,
NULL,eaID,0,Gold);
return;
}
if (ob==0 && b==0 && ((MaxH-Close[0])/Point)>=5 && (top==-1 || top==0))
{
OrderSend(Symbol(),OP_BUYSTOP,mlot,
MaxH+del*Point,5,MaxH+del*Point-stl*Point,MaxH+del*Point+tpl*Point,
NULL,eaID,0,Gold);
return;
}
if (ob==0 && b==0 && ((MaxH-Close[0])/Point)<=0 && (top==-1 || top==0))
{
OrderSend(Symbol(),OP_BUYSTOP,mlot,
Ask+del*Point,5,Ask+del*Point-stl*Point,Ask+del*Point+tpl*Point,
NULL,eaID,0,Gold);
return;
}
}
}
}
//-------------------------------------------------------END----------------------------------------------------------
Comments