MQL4 Make Gann zigzag indicator plot SR lines - mql4

Somebody has an ideia how to plot SR LINES when this zigzag based on gann angle changes?
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 DeepSkyBlue
#property indicator_color2 Black
//---- input parameters
extern int GSv_range=12;
//---- buffers
double GSv_sl[];
double GSv_m[];
//----
bool draw_up=0,draw_dn=0,initfl=0;
int fPoint_i,sPoint_i,s_up,s_dn,drawf,lb,idFile;
double h,l;
bool cur_h=0,cur_l=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_SECTION,STYLE_DOT);
//SetIndexStyle(1,DRAW_SECTION);
SetIndexBuffer(0,GSv_sl);
//SetIndexBuffer(1,GSv_m);
SetIndexEmptyValue(0,0.0);
//SetIndexEmptyValue(1,0.0);
FileDelete("Gann.txt");
idFile=FileOpen("Gann.txt",FILE_READ|FILE_WRITE," ");
//----
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();
int cb,limit,i;
//----
if( GSv_range<1 )
{
Alert("Èíäèêàòîð ðàññ÷èòûâàåò çíà÷åíèÿ /n ïðè ïàðàìåòðå GSv_range íå ìåíüøå 1!!!");
return(-1);
}
if( counted_bars<0 )
{
return(-1);
}
else
{
if( Bars-1-counted_bars<=0 )
{
limit=0;
}
else
{
limit=Bars-1-counted_bars;
}
}
//ïåðâîíà÷àëüíàÿ èíèöèàëèçàöèÿ
if( initfl!=1 )
{
myInit();
}
//FileWrite(idFile," 0. Áàðîâ íà ãðàôèêå "+Bars);
//öèêë ïî áàðàì
for( cb=limit;cb>=0;cb--)
{
if( cb==0 ) FileWrite(idFile,"---- èíäåêñ òåêóùåãî áàðà "+cb+" "+(Bars-1-cb)+" âðåìÿ "+TimeToStr(Time[cb])+" áàðîâ íà ãðàôèêå "+Bars);
//åñëè íà ïðåäûäóùåì áàðå áûë îòðèñîâàí ýêñòðåìóì
if( GSv_sl[cb+1]>0 && lb!=Bars-1-cb )
{
if( draw_up!=0 )
{
s_dn=0;
if( cb==0 ) FileWrite(idFile," 1. Áûë îòðèñîâàí ìàêñèìóì, ñ÷åò÷èê ìèíèìóìîâ îáíóëåí");
}
else
{
if( draw_dn!=0 )
{
s_up=0;
if( cb==0 ) FileWrite(idFile," 2. Áûë îòðèñîâàí ìèíèìóì, ñ÷åò÷èê ìàêñèìóìîâ îáíóëåí");
}
}
}
if( lb!=Bars-1-cb )
{
cur_h=0;
cur_l=0;
if( cb==0 ) FileWrite(idFile," 2.1 íîâûé áàð ôëàãè íàëè÷èÿ ìàêñèìóìà è ìèíèìóìà ñáðîøåíû");
}
if( cb>Bars-2-drawf || (High[cb]<=High[cb+1] && Low[cb]>=Low[cb+1]) )
{
if( cb==0 ) FileWrite(idFile," 3. Áàð ëèáî 'âíóòðåííèé', ëèáî äî ïåðâîãî ýêñòðåìóìà");
continue;
}
if( draw_up!=0 )
{
if( cb==0 ) FileWrite(idFile," 4. Èíäèêàòîð íàïðàâëåí ââåðõ");
//åñëè ëèíèÿ íàïðàâëåíà ââåðõ
if( High[cb]>h )
{
//åñëè äîñòèãíóò íîâûé ìàêñèìóì
h=High[cb];
cur_h=1;
if( cb==0 ) FileWrite(idFile," 5. Äîñòèãíóò íîâûé ìàêñèìóì = "+h+" cur_h "+cur_h);
}
if( Low[cb]<l )
{
//åñëè äîñòèãíóò íîâûé ìèíèìóì
l=Low[cb];
if( cb==0 ) FileWrite(idFile," 6. Äîñòèãíóò íîâûé ìèíèìóì = "+l);
//åñëè ýòî íå òîò æå ñàìûé áàð
if( lb!=Bars-1-cb || cur_l!=1 ) s_dn++;
cur_l=1;
if( cb==0 ) FileWrite(idFile," 7. Áàð íîâûé, ñ÷åò÷èê ìèíèìóìîâ óâåëè÷åí "+s_dn+" cur_l "+cur_l);
}
//åñëè ñ÷åò÷èêè ðàâíû
if( s_up==s_dn )
{
if( cb==0 ) FileWrite(idFile," 8. Ñ÷åò÷èêè ðàâíû");
//åñëè ïîñëåäíèé áàð îäíîâðåìåííî íîâûé ìàêñèìóì è ìèíèìóì
if( cur_h==cur_l && cur_l==1 )
{
if( cb==0 ) FileWrite(idFile," 9. Åñòü äâà ýêñòðåìóìà");
//åñëè ñâå÷à ìåäâåæüÿ
if( Close[cb]<=Open[cb] )
{
draw_up=0;
draw_dn=1;
fPoint_i=sPoint_i;
sPoint_i=Bars-1-cb;
GSv_sl[cb]=l;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 10. Ñâå÷à ìåäâåæüÿ, ëèíèÿ ââåðõ = "+draw_up+", ëèíèÿ âíèç,"+draw_dn+" fPoint_i = "+fPoint_i+" sPoint_i "+sPoint_i+" èíäèêàòîð = "+GSv_sl[cb]);
}
else
{
//åñëè ñâå÷à áû÷üÿ
sPoint_i=Bars-1-cb;
GSv_sl[cb]=h;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 11. Ñâå÷à áû÷üÿ, ëèíèÿ ââåðõ = "+draw_up+", ëèíèÿ âíèç,"+draw_dn+" fPoint_i = "+fPoint_i+" sPoint_i "+sPoint_i+" èíäèêàòîð = "+GSv_sl[cb]);
}
}
else
{
//åñëè ïîñëåäíèé áàð òîëüêî íîâûé ìàêñèìóì
if( cur_h==1 )
{
sPoint_i=Bars-1-cb;
GSv_sl[cb]=h;
l=Low[cb];
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 12. Òîëüêî ìàêñèìóì, èíäèêàòîð = "+GSv_sl[cb]+" sPoint_i "+sPoint_i+" l "+l);
}
else
{
if( cur_l==1 )
{
//åñëè ïîñëåäíèé áàð òîëüêî íîâûé ìèíèìóì
draw_up=0;
draw_dn=1;
fPoint_i=sPoint_i;
sPoint_i=Bars-1-cb;
GSv_sl[cb]=l;
h=High[cb];
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 13. Òîëüêî ìèíèìóì, èíäèêàòîð = "+GSv_sl[cb]+" fPoint_i "+fPoint_i+" sPoint_i "+sPoint_i+" draw_up "+draw_up+" draw_dn "+draw_dn+" h "+h);
}
}
}
}
else
{
//èíà÷å åñëè ñìåíû íàïðàâëåíèÿ íåò ÿâíî (ñ÷åò÷èê Dn ñâå÷åé íå ðàâåí GSv_range)
if( cb==0 ) FileWrite(idFile," 14. Ñ÷åò÷èêè íå ðàâíû");
//åñëè äîñòèãíóò íîâûé ìàêñèìóì
if( cur_h==1 )
{
sPoint_i=Bars-1-cb;
GSv_sl[cb]=h;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
l=Low[cb];
if( cb==0 ) FileWrite(idFile," 15. Åñòü íîâûé ìàêñèìóì, èíäèêàòîð "+GSv_sl[cb]+" sPoint_i "+sPoint_i+" l "+l);
}
}
}
else
{
//åñëè ëèíèÿ íàïðàâëåíà âíèç
if( cb==0 ) FileWrite(idFile," 16. Èíäèêàòîð íàïðàâëåí âíèç");
if( High[cb]>h )
{
//åñëè äîñòèãíóò íîâûé ìàêñèìóì
h=High[cb];
if( cb==0 ) FileWrite(idFile," 17. Äîñòèãíóò íîâûé ìàêñèìóì "+h);
if( lb!=Bars-1-cb || cur_h!=1 ) s_up++;
cur_h=1;
//åñëè ýòî íå òîò æå ñàìûé áàð
if( cb==0 ) FileWrite(idFile," 18. Íîâûé áàð, ñ÷åò÷èê ìàêñèìóìîâ óâåëè÷åí "+s_up+" cur_h "+cur_h+" h "+h);
}
if( Low[cb]<l )
{
//åñëè äîñòèãíóò íîâûé ìèíèìóì
l=Low[cb];
cur_l=1;
if( cb==0 ) FileWrite(idFile," 19. Äîñòèãíóò íîâûé ìèíèìóì "+l+" cur_l "+cur_l);
}
//åñëè ñ÷åò÷èêè ðàâíû
if( s_up==s_dn )
{
if( cb==0 ) FileWrite(idFile," 20. Ñ÷åò÷èêè ðàâíû");
//åñëè ïîñëåäíèé áàð îäíîâðåìåííî íîâûé ìàêñèìóì è ìèíèìóì
if( cur_h==cur_l && cur_l==1 )
{
if( cb==0 ) FileWrite(idFile," 21. Åñòü äâà ýêñòðåìóìà");
//åñëè ñâå÷à ìåäâåæüÿ
if( Close[cb]<=Open[cb] )
{
sPoint_i=Bars-1-cb;
GSv_sl[cb]=l;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 22. Ñâå÷à ìåäâåæüÿ, èíäèêàòîð "+GSv_sl[cb]+" sPoint_i "+sPoint_i);
}
else
{
//åñëè ñâå÷à áû÷üÿ
draw_up=1;
draw_dn=0;
fPoint_i=sPoint_i;
sPoint_i=Bars-1-cb;
GSv_sl[cb]=h;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 23. Ñâå÷à áû÷üÿ, èíäèêàòîð "+GSv_sl[cb]+" draw_up "+draw_up+" draw_dn "+draw_dn+" sPoint_i "+sPoint_i+" fPoint_i "+fPoint_i);
}
}
else
{
//åñëè ïîñëåäíèé áàð òîëüêî íîâûé ìàêñèìóì
if( cur_h==1 )
{
draw_up=1;
draw_dn=0;
fPoint_i=sPoint_i;
sPoint_i=Bars-1-cb;
GSv_sl[cb]=h;
l=Low[cb];
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 24. Òîëüêî ìàêñèìóì, èíäèêàòîð "+GSv_sl[cb]+" draw_up "+draw_up+" draw_dn "+draw_dn+" sPoint_i "+sPoint_i+" fPoint_i "+fPoint_i+" l "+l);
}
else
{
if( cur_l==1 )
{
//åñëè ïîñëåäíèé áàð òîëüêî íîâûé ìèíèìóì
sPoint_i=Bars-1-cb;
GSv_sl[cb]=l;
h=High[cb];
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
if( cb==0 ) FileWrite(idFile," 25. Òîëüêî ìèíèìóì, èíäèêàòîð "+GSv_sl[cb]+" sPoint_i "+sPoint_i+" h "+h);
}
}
}
}
else
{
//èíà÷å åñëè ñìåíû íàïðàâëåíèÿ íåò ÿâíî (ñ÷åò÷èê Up ñâå÷åé íå ðàâåí GSv_range)
if( cb==0 ) FileWrite(idFile," 26. Ñ÷åò÷èêè íå ðàâíû");
//åñëè äîñòèãíóò íîâûé ìèíèìóì
if( cur_l==1 )
{
sPoint_i=Bars-1-cb;
GSv_sl[cb]=l;
for( i=cb+1;i<Bars-1-fPoint_i;i++ )
{
GSv_sl[i]=0;
}
h=High[cb];
if( cb==0 ) FileWrite(idFile," 27. Äîñòèãíóò íîâûé ìèíèìóì, èíäèêàòîð "+GSv_sl[cb]+" sPoint_i "+sPoint_i+" h "+h);
}
}
}
if( lb!=Bars-1-cb ) lb=Bars-1-cb;
}
//----
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
FileClose(idFile);
//----
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// Ôóíêöèÿ íà÷àëüíîé èíèöèàëèçàöèè èíäèêàòîðà |
//+------------------------------------------------------------------+
void myInit()
{
//----
int cb;
fPoint_i=0;
h=High[Bars-1];
l=Low[Bars-1];
for( cb=Bars-2;cb>=0;cb--)
{
if( High[cb]>High[cb+1] || Low[cb]<Low[cb+1] )
{
if( High[cb]>h && High[cb]>High[cb+1] )
{
s_up++;
}
if( Low[cb]<l && Low[cb]<Low[cb+1] )
{
s_dn++;
}
}
else
{
continue;
}
if( s_up==s_dn && s_up==GSv_range )
{
h=High[cb];
l=Low[cb];
sPoint_i=Bars-1-cb;
if( Close[cb]>=Open[cb] )
{
s_dn=0;
GSv_sl[Bars-1]=Low[Bars-1];
GSv_sl[cb]=High[cb];
draw_up=1;
break;
}
else
{
s_up=0;
GSv_sl[Bars-1]=High[Bars-1];
GSv_sl[cb]=Low[cb];
draw_dn=1;
break;
}
}
else
{
h=High[cb];
l=Low[cb];
sPoint_i=Bars-1-cb;
if( s_up==GSv_range )
{
s_dn=0;
GSv_sl[Bars-1]=Low[Bars-1];
GSv_sl[cb]=High[cb];
draw_up=1;
break;
}
else
{
if( s_dn==GSv_range )
{
s_up=0;
GSv_sl[Bars-1]=High[Bars-1];
GSv_sl[cb]=Low[cb];
draw_dn=1;
break;
}
}
}
}
initfl=1;
drawf=sPoint_i;
//----
//return(0);
}
//+------------------------------------------------------------------+

Related

Playwright's page.evaluate always return undefined

this is my code.
very simple, I want to know if an element is in viewport.
for some reason I can't understand I keep getting undefined.
the element exists but nothing happens
in the I see the x but the q is never seen.
async function isItemInViewport( page ) {
console.log( 'x' );
await page.evaluate( () => {
console.log( 'q' );
const lastMenuItem = document.querySelectorAll( '.nav-menu--dropdown.nav-menu__container .lastitem-class-for-playwright-test' )[ 0 ].getBoundingClientRect();
console.log(lastMenuItem );
let isInViewport = false;
if (
lastMenuItem.top >= 0 &&
lastMenuItem.left >= 0 &&
lastMenuItem.bottom <= ( window.innerHeight || document.documentElement.clientHeight ) &&
lastMenuItem.right <= ( window.innerWidth || document.documentElement.clientWidth )
) {
isInViewport = true;
}
return isInViewport;
} );
}
This is what I end up doing:
async function isItemInViewport( page, item ) {
return await page.evaluate( ( item ) => {
let isVisible = false;
const element = document.querySelector( item );
if ( element ) {
const rect = element.getBoundingClientRect();
if ( rect.top >= 0 && rect.left >= 0 ) {
const vw = Math.max( document.documentElement.clientWidth || 0, window.innerWidth || 0 );
const vh = Math.max( document.documentElement.clientHeight || 0, window.innerHeight || 0 );
if ( rect.right <= vw && rect.bottom <= vh ) {
isVisible = true;
}
}
}
return isVisible;
}, item );
}
And this is the function call:
// Assertion
const item = '.item-css-class';
await expect( await isItemInViewport( page, item ) ).toBeTruthy();

Expert Advisor is not opening trades

I tried to create an EA in mql4 which opens and close the trade position as per condition given, but it is not opening the trade after mating the conditions, EA Works till signal which shows buy and sell and after that nothing happens. How can I debug this?
void CloseBuyPosition()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
string Cp = OrderSymbol();
if (_Symbol == Cp)
if (OrderType() == OP_BUY)
{
OrderClose(OrderTicket(), OrderLots(), Bid, 3, NULL);
}
}
}
void CloseSellPosition()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
string Cp = OrderSymbol();
if (_Symbol == Cp)
if (OrderType() == OP_SELL)
{
OrderClose(OrderTicket(), OrderLots(), Ask, 3, NULL);
}
}
}
void OnTick()
{
string signal = "";
double Sar = iSAR(_Symbol, _Period, 0.02, 0.2, 0);
if (Sar < Low[1] && Open[1] < Close[1])
{
signal = "buy";
}
if (Sar > High[1] && Open[1] > Close[1])
{
signal = "sell";
}
if (signal == "buy" && OrdersTotal() == 0)
OrderSend(_Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green);
if (signal == "sell" && OrdersTotal() == 0)
OrderSend(_Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red);
Comment("The Signal is :", signal);
if (Open[1] > Close[1] && OrdersTotal() > 0)
CloseBuyPosition();
if (Open[1] < Close[1] && OrdersTotal() > 0)
CloseSellPosition();
}
Step 0:check, whether your EA was launched inside MetaTrader4 Terminal with an active permission to actually do trades.
Step 1:check the code, for having at least some elementary self-debugging tools ( GetLastError() and Print() are way better than intermittent and self-destroying, i.e. having Zero-depth of history GUI-text inside but a last visible Comment()
Step 2:Analyze the logs, where all printed details will help you trace the root cause ( Broker-rejections, closed Market, flawed price-levels and many of the possible reasons for an OrderSend()-call to get rejected )
int OrderSend( string symbol, // symbol
int cmd, // operation
double volume, // volume
double price, // price
int slippage, // slippage
double stoploss, // stop loss <------------ PRICE-DOMAIN levels, not INT-s
double takeprofit, // take profit <---------- PRICE-DOMAIN levels, not INT-s
string comment = NULL, // comment
int magic = 0, // magic number
datetime expiration = 0, // pending order expiration
color arrow_color = clrNONE// color
);
void OnTick()
{
/* string signal = "";
double Sar = iSAR( _Symbol, _Period, 0.02, 0.2, 0 );
if ( Sar < Low[1] && Open[1] < Close[1] ) signal = "buy";
if ( Sar > High[1] && Open[1] > Close[1] ) signal = "sell";
if ( signal == "buy" && OrdersTotal() == 0 ) OrderSend( _Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green );
if ( signal == "sell" && OrdersTotal() == 0 ) OrderSend( _Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red );
Comment( "The Signal is :", signal );
if ( Open[1] > Close[1] && OrdersTotal() > 0 ) CloseBuyPosition();
if ( Open[1] < Close[1] && OrdersTotal() > 0 ) CloseSellPosition();
*/
static int count_of_NOPs = 0;
if ( OrdersTotal() == 0 )
{ if ( Open[1] < Close[1]
&& Low[1] > iSAR( _Symbol, _Period, 0.02, 0.2, 0 )
) {
int rc = OrderSend( _Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green );
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID TRY OrderSend( OP_BUY ) -> RESULTING RetCode ( tkt# ) == %d [yield GetLastError() == %d]",
rc,
GetLastError()
)
);
count_of_NOPs = 0; //------------------------------ .RESET
return; //------------------------------------------^ J.I.T./RET
}
if ( Open[1] > Close[1]
&& High[1] < iSAR( _Symbol, _Period, 0.02, 0.2, 0 )
) {
int rc = OrderSend( _Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red );
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID TRY OrderSend( OP_SELL ) -> RESULTING RetCode ( tkt# ) == %d [yield GetLastError() == %d]",
rc,
GetLastError()
)
);
if ( )
count_of_NOPs = 0; //------------------------------ .RESET
return; //------------------------------------------^ J.I.T./RET
}
/* OTHERWISE: */
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID NOP... (for %d time)",
++count_of_NOPs
)
);
// */
}
else
{ if ( Open[1] > Close[1] ) { Print( StringFormat( "HAVING %d ORDERS ACTIVE... WILL TRY CloseBuyPosition()...",
OrdersTotal()
)
);
CloseBuyPosition();
count_of_NOPs = 0; //---------- .RESET
return; //----------------------^ J.I.T./RET
}
if ( Open[1] < Close[1] ) { Print( StringFormat( "HAVING %d ORDERS ACTIVE... WILL TRY CloseSellPosition()...",
OrdersTotal()
)
);
CloseSellPosition();
count_of_NOPs = 0; //---------- .RESET
return; //----------------------^ J.I.T./RET
}
/* OTHERWISE: */
Print( StringFormat( "HAVING %d ORDERS ACTIVE... DID NOP... (for %d time)",
OrdersTotal(),
++count_of_NOPs
)
);
// */
}

How can I cancel a trade when another is open and keep the open trade for a given duration?

I have written the code below that opens a buy and sell trade (a certain number of pips above and below the ask and bid price) at a specific time.
How can I close/cancel one immediately when the other is opened?
How can I close the opened trade if it's say X pips in profit or after a minute (depending on which condition is reached first)?
I'm a not too sure I've done the right thing in the code below and would really appreciate some help.
double spread = Ask-Bid;
extern datetime time;
extern int pipGap = 7;
extern int lotSize = 0.01;
extern int closeTimeInSeconds = 60;
int start() {
if (TimeCurrent() >= StrToTime(time)){
OrderSend(Symbol(),OP_BUYSTOP,lotSize, Ask + Point*pipGap, 0,0,0);
OrderSend(Symbol(),OP_SELLSTOP,lotSize, Bid - Point*pipGap, 0,0,0);
}
for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
OrderSelect(pos, SELECT_BY_POS)
){
int duration = TimeCurrent() - OrderOpenTime();
if (duration >= closeTimeInSeconds)
OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(),
3*Point);
}
return(0);
}
AUTOMATED NEWS TRADING
What you (#iGetIt ) are looking for is a rudimentary News Trading bot. Here's a diluted implementation for it.
In the more advanced stages, you will need to automatically download news and auto-trade base on the affected pairs, track volatility (to avoid swings), sync your PC time (Windows date/time is NOT accurate and news trading need to be synced to the millisecond level). Track your broker server response time, implement Trailing-StopLoss (for improved profit), implement slide-in-orders (multiple stop orders to catch huge spikes), calculate order-set profitability (to know when to close all the orders when price retrace), etc etc.
Anyway, here's a basic version that you can play with (based on the Bounty requirements):
Opens buy + sell stop-orders at specific time.
Configurable number of pips AWAY from current ask/bid.
Implements OCO (One Cancels the Other).
Closes executed trades with x-pip profit (aka TP level).
Closes executed or outstanding stop-orders after x-seconds.
Visual: To show that it executes in time (this is Asian time, so liquidity is low, so +- a few seconds before price ticks).
Closing: It closes automatically based on the settings.
SOURCE CODE: And this is the complete MQL4 source-code for it.
(UPDATED 15May19 1045 GMT+8) to fix bug as reported in the closing of executed orders after TTL.
//+------------------------------------------------------------------+
//| SO55930471.mq4 |
//| Copyright 2019, Joseph Lee, joseph.lee#fs.com.my |
//| TELEGRAM #JosephLee74 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, Joseph Lee, TELEGRAM #JosephLee74"
#property link "http://www.fs.com.my"
#property version "1.00"
#property strict
//-------------------------------------------------------------------
// APPLICABLE PARAMETERS
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// NEWS IMPACT SELECTION
//===================================================================
extern string vsEAComment = "Telegram #JosephLee74"; //Ego trip
extern datetime vdTradeStartInGMT = D'2019.5.14 06:00'; //When to trade (GMT)
extern int viStopOrderLevelInPip = 5; // StopOrder distance from ask/bid (pips)
extern double viFixLots = 0.01; // Lot size
extern int viStopLossInPip = 20; // StopLoss (pips)
extern int viTargetProfitInPip = 100; // TargetProfit (pips)
extern int viDeleteStopOrderAfterInSec = 30; // StopOrder TTL (sec)
extern int viDeleteOpenOrderAfterInSec = 300; // Executed Order TTL (sec)
extern int viMaxSlippageInPip = 2; // Max Slippage (pip)
//-------------------------------------------------------------------
// System Variables
//-------------------------------------------------------------------
int viMagicId = 0;
double viPipsToPrice = 0.0001;
double viPipsToPoint = 1;
int viBuyStopTicket = -1;
int viSellStopTicket = -1;
int viBuyOrderTicket = -1;
int viSellOrderTicket = -1;
string vsDisplay = "EVENT-TRADER v1.01 - ";
//-------------------------------------------------------------------
//+------------------------------------------------------------------+
//| EA Initialization function
//+------------------------------------------------------------------+
int init() {
ObjectsDeleteAll(); Comment("");
// Caclulate PipsToPrice & PipsToPoints (old sytle, but works)
if((Digits == 2) || (Digits == 3)) {viPipsToPrice=0.01;}
if((Digits == 3) || (Digits == 5)) {viPipsToPoint=10;}
viMagicId = vdTradeStartInGMT;
start();
return(0);
}
//+------------------------------------------------------------------+
//| EA Stand-Down function
//+------------------------------------------------------------------+
int deinit() {
ObjectsDeleteAll();
return(0);
}
//============================================================
// MAIN EA ROUTINE
//============================================================
int start() {
//==========================================
//MANAGE ROBOT EXPIRY
//==========================================
if( TimeCurrent() > D'2020.1.1' ) {
Comment(vsDisplay + "EXPIRED. Please contact josephfhlee74 at gmail dot com"); // Who am I kidding?
return(0);
}
ResetLastError();
// Exit the routine if it is not time to trade yet.
if(TimeGMT() < vdTradeStartInGMT) {
// Show a count-down timer to the trading time.
Comment(vsDisplay +
"[" + TimeToStr(TimeGMT()) + " GMT] " +
IntegerToString(int(vdTradeStartInGMT - TimeGMT())) + " sec to [" +
TimeToStr(vdTradeStartInGMT) + " GMT]"
);
return(0);
}
viBuyStopTicket = -1;
viSellStopTicket = -1;
viBuyOrderTicket = -1;
viSellOrderTicket = -1;
//=========================================================
//FIND *OPENED* BUY/SELL PENDING ORDERS
//---------------------------------------------------------
for( int i=OrdersTotal()-1; i>=0; i-- ) {
if(OrderSelect( i, SELECT_BY_POS, MODE_TRADES ))
if( OrderSymbol() == Symbol() )
if( OrderMagicNumber() == viMagicId) {
if( OrderType() == OP_BUYSTOP )
viBuyStopTicket = OrderTicket();
if( OrderType() == OP_SELLSTOP )
viSellStopTicket = OrderTicket();
if( OrderType() == OP_BUY )
viBuyOrderTicket = OrderTicket();
if( OrderType() == OP_SELL )
viSellOrderTicket = OrderTicket();
}
}
//=========================================================
//FIND *CLOSED* BUY/SELL ORDERS FOR THIS EVENT
//---------------------------------------------------------
for(int i=OrdersHistoryTotal()-1; i>=0; i--) {
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
if(OrderSymbol() == Symbol())
if(OrderMagicNumber() == viMagicId) {
if( OrderType() == OP_BUYSTOP )
viBuyStopTicket = OrderTicket();
if( OrderType() == OP_SELLSTOP )
viSellStopTicket = OrderTicket();
if( OrderType() == OP_BUY )
viBuyOrderTicket = OrderTicket();
if( OrderType() == OP_SELL )
viSellOrderTicket = OrderTicket();
}
}
// The above 2 sections will ensure that each event will only be executed once.
// If orders are cancelled or closed for whatever reason, they will never be open again.
string vsVerbose = vsDisplay + "[GMT " + TimeToStr(TimeGMT()) + "] Executing ..."
"\nActive BUYSTOP: " + viBuyStopTicket +
" | Active SELLSTOP: " + viSellStopTicket +
"" +
"\nActive BUY: " + viBuyOrderTicket +
" | Active SELL: " + viSellOrderTicket;
Comment(vsVerbose);
//=========================================================
// HANDLES OCO (One-Cancels-the-Other)
//---------------------------------------------------------
// BUY Order EXISTS, cancels all SellStops
if( viBuyOrderTicket != -1 ) {
for( int i=OrdersTotal()-1; i>=0; i-- ) {
if(OrderSelect( i, SELECT_BY_POS, MODE_TRADES ))
if( OrderSymbol() == Symbol() )
if( OrderMagicNumber() == viMagicId)
if( OrderType() == OP_SELLSTOP )
OrderDelete(OrderTicket());
}
}
// SELL Order EXISTS, cancels all BuyStops
if( viSellOrderTicket != -1 ) {
for( int i=OrdersTotal()-1; i>=0; i-- ) {
if(OrderSelect( i, SELECT_BY_POS, MODE_TRADES ))
if( OrderSymbol() == Symbol() )
if( OrderMagicNumber() == viMagicId)
if( OrderType() == OP_BUYSTOP )
OrderDelete(OrderTicket());
}
}
//=========================================================
//CLOSE EXPIRED STOP/EXECUTED ORDERS
//---------------------------------------------------------
for( int i=OrdersTotal()-1; i>=0; i-- ) {
if(OrderSelect( i, SELECT_BY_POS, MODE_TRADES ))
if( OrderSymbol() == Symbol() )
if( OrderMagicNumber() == viMagicId) {
if( (OrderType() == OP_BUYSTOP) || (OrderType() == OP_SELLSTOP) )
if((TimeCurrent()-OrderOpenTime()) >= viDeleteStopOrderAfterInSec)
OrderDelete(OrderTicket());
if( (OrderType() == OP_BUY) || (OrderType() == OP_SELL) )
if((TimeCurrent()-OrderOpenTime()) >= viDeleteOpenOrderAfterInSec) {
// For executed orders, need to close them
double closePrice = 0;
RefreshRates();
if(OrderType() == OP_BUY)
closePrice = Bid;
if(OrderType() == OP_SELL)
closePrice = Ask;
OrderClose(OrderTicket(), OrderLots(), closePrice, int(viMaxSlippageInPip*viPipsToPoint), clrWhite);
}
}
}
//===================================================================
//OPEN STOP ORDERS IF NO EXISTING nor CLOSED NO BUY/SELL STOP/ORDERS
//-------------------------------------------------------------------
// Do NOT execute (place new orders) if it is past the trading window.
if(TimeGMT() >= (vdTradeStartInGMT+viDeleteStopOrderAfterInSec))
{
Comment(vsDisplay + "[" + TimeToStr(TimeGMT()) + " GMT] " + "Already passed execution time.");
return(0);
}
// Place BuyStop if not exists; and no executed-Buy order
if( (viBuyStopTicket == -1) && (viBuyOrderTicket == -1)) {
RefreshRates();
viFixLots = NormalizeDouble(viFixLots, 2);
double viPrice = NormalizeDouble(Ask + (viStopOrderLevelInPip*viPipsToPrice), Digits);
double viSL = viPrice - (viStopLossInPip*viPipsToPrice);
double viTP = viPrice + (viTargetProfitInPip*viPipsToPrice);
viBuyStopTicket = OrderSend(Symbol(), OP_BUYSTOP, viFixLots
, viPrice
, int(viMaxSlippageInPip*viPipsToPoint)
, viSL, viTP
, vsEAComment, viMagicId, 0, Blue);
if(viBuyStopTicket == -1)
Print("Error executing BuyStop [" + IntegerToString(GetLastError()) + "]." );
}
// Place SellStop if not exists; and no executed-Sell order
if( (viSellStopTicket == -1) && (viSellOrderTicket == -1) ) {
RefreshRates();
viFixLots = NormalizeDouble(viFixLots, 2);
double viPrice = NormalizeDouble(Bid - (viStopOrderLevelInPip*viPipsToPrice), Digits);
double viSL = viPrice + (viStopLossInPip*viPipsToPrice);
double viTP = viPrice - (viTargetProfitInPip*viPipsToPrice);
viSellStopTicket = OrderSend(Symbol(), OP_SELLSTOP, viFixLots
, viPrice
, int(viMaxSlippageInPip*viPipsToPoint)
, viSL, viTP
, vsEAComment, viMagicId, 0, Red);
if(viSellStopTicket == -1)
Print("Error executing SellStop [" + IntegerToString(GetLastError()) + "]." );
}
return(0);
}
#property strict
//---
input datetime InpTime1=D'2019.05.01 00:00'; //time to enter the trade, just as an example
input double InpPipsDist=10; //distance in pips to place BS&SS OCO-orders
input int InpCloseSeconds=60; //close time, seconds since main order is sent
input double InpProfitPips=1.; //profit in pips to close all.
input double InpLotSize=0.1; //lot size
input int InpMagicNumber=123456789; //magic number
// ---
#include <Arrays\ArrayObj.mqh>
bool firstOrderOpen;
double PIP;
CArrayObj *ordersList;
// ---
class C2Orders : public CObject
{
private:
int m_ticket1;
int m_ticket2;
datetime m_timeStart;//OrderOpenTime of the two tickets might be different,TimeCurrent() is used as time they are open.
bool m_activated;
void checkTicket(const int ticket) //if one order is open, another is deleted.
{
if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET))
{
if(OrderType()<=OP_SELL)
{
if(ticket==m_ticket1)
{
if(OrderDelete(m_ticket2))
printf("%i: failed to delete#%d. error=%d",__LINE__,m_ticket2,_LastError);
m_ticket2=-1;
}
else
{
if(!OrderDelete(m_ticket1))
printf("%i: failed to delete#%d. error=%d",__LINE__,m_ticket1,_LastError);
m_ticket1=-1;
}
m_activated=true;
}
}
}
double getPnlPips(const int ticket)const
{
if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET))
{
return (OrderProfit()>0 ? 1 : -1)*fabs(OrderOpenPrice()-OrderClosePrice());
}
return 0;
}
bool try2closeByPnl()const
{
const double pnl=getPnlPips(m_ticket1)+getPnlPips(m_ticket2);
if(pnl-InpProfitPips*PIP>0)
{
printf("%i : pnl=%.5f vs %.5f target. closing the tickets",__LINE__,pnl,InpProfitPips*PIP);
close(m_ticket1);
close(m_ticket2);
return(true);
}
return(false);
}
bool try2closeByTime()const
{
if(TimeCurrent()-m_timeStart-InpCloseSeconds>=0)
{
if(!OrderDelete(m_ticket1))printf("%i: failed to delete#%d. error=%d",__LINE__,m_ticket1,_LastError);
if(!OrderDelete(m_ticket2))printf("%i: failed to delete#%d. error=%d",__LINE__,m_ticket2,_LastError);
return(true);
}
return(false);
}
void close(const int ticket)const
{
if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET))
{
RefreshRates();
if(OrderClose(ticket,OrderLots(),OrderClosePrice(),1))
printf("%i: failed to close#%d. error=%d",__LINE__,ticket,_LastError);
}
}
public:
C2Orders(const int ticket1,const int ticket2,const datetime time):
m_ticket1(ticket1),m_ticket2(ticket2),m_activated(false),m_timeStart(time){}
~C2Orders(){}
bool check() //returns FALSE if deleting the object
{
if(!m_activated)
{
checkTicket(m_ticket1);
checkTicket(m_ticket2);
}
if(m_activated)
{
if(try2closeByPnl())
return(false);
}
else
{
if(try2closeByTime())
return(false);
}
return true;
}
};
//+------------------------------------------------------------------+
int OnInit()
{
firstOrderOpen=false;
PIP=_Point*(_Digits%2==1 ? 10 : 1); //does not work for GOLD and indexes, good for FX.
ordersList=new CArrayObj();
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
delete(ordersList);
}
void OnTick()
{
if(!firstOrderOpen && TimeCurrent()>=InpTime1)
{
RefreshRates();
const int ticketBS=OrderSend(_Symbol,OP_BUYSTOP,InpLotSize,NormalizeDouble(Ask+InpPipsDist*PIP,_Digits),0,0,0,NULL,InpMagicNumber);
const int ticketSS=OrderSend(_Symbol,OP_SELLSTOP,InpLotSize,NormalizeDouble(Bid-InpPipsDist*PIP,_Digits),0,0,0,NULL,InpMagicNumber);
C2Orders *oco=new C2Orders(ticketBS,ticketSS,TimeCurrent());
ordersList.Add(oco);
firstOrderOpen=true;
}
if(firstOrderOpen)
{
C2Orders* oco;
for(int i=ordersList.Total()-1;i>=0;i--)//of course you have only one instance, but in real world you may need to loop over them.
{
oco=ordersList.At(i);
if(!oco.check())
ordersList.Delete(i);
}
if(ordersList.Total()==0)
ExpertRemove();//just to finish the test faster.
}
}

mql4 check if order exists executed multiple times

I'm using this code to check if orders are existing for the price buy1 and sell1 in my code.
Somehow some orders get executed twice.
Shouldn't happen because i'm checking if there is any open order with the same takeprofit.
Anyone able to see whats wrong?
bool CheckBuyOrder1(double buy1_tp){
for( int i = 0 ; i < OrdersTotal() - 1 ; i++ ) {
OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
if( OrderTakeProfit() == buy1_tp && OrderComment() == "buy" )
return(true);
}
return(false);
}
bool CheckSellOrder1(double sell1_tp){
for( int i = 0 ; i < OrdersTotal() - 1 ; i++ ) {
OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
if( OrderTakeProfit() == sell1_tp && OrderComment() == "sell" )
return(true);
}
return(false);
}
int totalOrders = OrdersTotal();
void OnTick()
{
if(totalOrders != OrdersTotal()){
double vbid = MarketInfo("EURUSD",MODE_BID);
double bid = NormalizeDouble(vbid, 3);
double market_buy_tp = bid;
double buy1= bid + 0.002;
double buy1_tp= bid + 0.003;
if(CheckOpenOrders1(market_buy_tp)==false && CheckBuyOrder1(buy1_tp)==false){
int ticket9=OrderSend(Symbol(),OP_BUYSTOP,Lots,buy1,MaxSlippage,0,buy1_tp,"buy",16380,0,clrGreen);
}
double market_sell_tp = bid;
double sell1 = bid - 0.003;
double sell1_tp= bid - 0.004;
if(CheckOpenOrdersSell1(market_sell_tp)==false && CheckSellOrder1(sell1_tp)==false ){
int ticket19=OrderSend(Symbol(),OP_SELLSTOP,Lots,sell1,MaxSlippage,0,sell1_tp,"sell",16380,0,clrGreen);
}
totalOrders = OrdersTotal();
}}
Whenever you try to compare an OrderTakeProfit() value with some other double - keep in mind rounding and float representation.
E.g. if you need to compare 0.10 with another double that you believe is 0.10 - you might be surprised that 0.10 is 0.09(9)6 or 0.10(0)4
That is why sometimes you might not find such an order.
double o = Point / 2; // initialize in OnInit(), declare in global vars
...
bool CheckOrderBuy( double tp ){
for ( int i = OrdersTotal() - 1; i >= 0; i-- ){
if ( !OrderSelect( i, SELECT_BY_POS ) )continue;
if ( fabs( OrderTakeProfit() - tp ) < o
&& OrderType() == OP_BUY
) return true;
}
return false;
}

FaceDetect OpenCV2.1 sample, Access violation writing location 0x00000000

I try to run facedetect opencv sample with vs2010.
debug result "Unhandled exception at 0x53fa42bf in facedetect.exe: 0xC0000005: Access violation writing location 0x00000000."
Here is the code
txt file: http://ebooks-libs.com/backup/facedetect-opencv2.1.txt
cpp file: http://ebooks-libs.com/backup/facedetect.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#define CV_NO_BACKWARD_COMPATIBILITY
#include "cv.h"
#include "highgui.h"
#ifdef _EiC
#define WIN32
#endif
using namespace std;
using namespace cv;
void detectAndDraw( Mat& img,
CascadeClassifier& cascade, CascadeClassifier& nestedCascade,
double scale);
String cascadeName ="./data/haarcascades/haarcascade_frontalface_alt.xml";
String nestedCascadeName ="./data/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
int main( int argc, const char** argv )
{
CvCapture* capture = 0;
Mat frame, frameCopy, image;
const String scaleOpt = "--scale=";
size_t scaleOptLen = scaleOpt.length();
const String cascadeOpt = "--cascade=";
size_t cascadeOptLen = cascadeOpt.length();
const String nestedCascadeOpt = "--nested-cascade";
size_t nestedCascadeOptLen = nestedCascadeOpt.length();
String inputName;
CascadeClassifier cascade, nestedCascade;
double scale = 1;
for( int i = 1; i < argc; i++ )
{
if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
cascadeName.assign( argv[i] + cascadeOptLen );
else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 )
{
if( argv[i][nestedCascadeOpt.length()] == '=' )
nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 );
if( !nestedCascade.load( nestedCascadeName ) )
cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
}
else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )
{
if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 )
scale = 1;
}
else if( argv[i][0] == '-' )
{
cerr << "WARNING: Unknown option %s" << argv[i] << endl;
}
else
inputName.assign( argv[i] );
}
if( !cascade.load( cascadeName ) )
{
cerr << "ERROR: Could not load classifier cascade" << endl;
cerr << "Usage: facedetect [--cascade=\"<cascade_path>\"]\n"
" [--nested-cascade[=\"nested_cascade_path\"]]\n"
" [--scale[=<image scale>\n"
" [filename|camera_index]\n" ;
return -1;
}
if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' );
else if( inputName.size() )
{
image = imread( inputName, 1 );
if( image.empty() )
capture = cvCaptureFromAVI( inputName.c_str() );
}
else
image = imread( "lena.jpg", 1 );
cvNamedWindow( "result", 1 );
if( capture )
{
for(;;)
{
IplImage* iplImg = cvQueryFrame( capture );
frame = iplImg;
if( frame.empty() )
break;
if( iplImg->origin == IPL_ORIGIN_TL )
frame.copyTo( frameCopy );
else
flip( frame, frameCopy, 0 );
detectAndDraw( frameCopy, cascade, nestedCascade, scale );
if( waitKey( 10 ) >= 0 )
goto _cleanup_;
}
waitKey(0);
_cleanup_:
cvReleaseCapture( &capture );
}
else
{
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale );
waitKey(0);
}
else if( !inputName.empty() )
{
/* assume it is a text file containing the
list of the image filenames to be processed - one per line */
FILE* f = fopen( inputName.c_str(), "rt" );
if( f )
{
char buf[1000+1];
while( fgets( buf, 1000, f ) )
{
int len = (int)strlen(buf), c;
while( len > 0 && isspace(buf[len-1]) )
len--;
buf[len] = '\0';
cout << "file " << buf << endl;
image = imread( buf, 1 );
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale );
c = waitKey(0);
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
}
fclose(f);
}
}
}
cvDestroyWindow("result");
return 0;
}
void detectAndDraw( Mat& img,
CascadeClassifier& cascade, CascadeClassifier& nestedCascade,
double scale)
{
int i = 0;
double t = 0;
vector<Rect> faces;
const static Scalar colors[] = { CV_RGB(0,0,255),
CV_RGB(0,128,255),
CV_RGB(0,255,255),
CV_RGB(0,255,0),
CV_RGB(255,128,0),
CV_RGB(255,255,0),
CV_RGB(255,0,0),
CV_RGB(255,0,255)} ;
Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
cvtColor( img, gray, CV_BGR2GRAY );
resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
t = (double)cvGetTickCount();
cascade.detectMultiScale( smallImg, faces,1.1, 2, 0 |CV_HAAR_SCALE_IMAGE,Size(30, 30) );
//|CV_HAAR_FIND_BIGGEST_OBJECT
//|CV_HAAR_DO_ROUGH_SEARCH
t = (double)cvGetTickCount() - t;
printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) );
for( vector<Rect>::const_iterator r = faces.begin(); r != faces.end(); r++, i++ )
{
Mat smallImgROI;
vector<Rect> nestedObjects;
Point center;
Scalar color = colors[i%8];
int radius;
center.x = cvRound((r->x + r->width*0.5)*scale);
center.y = cvRound((r->y + r->height*0.5)*scale);
radius = cvRound((r->width + r->height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg(*r);
nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
1.1, 2, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
//|CV_HAAR_DO_ROUGH_SEARCH
//|CV_HAAR_DO_CANNY_PRUNING
|CV_HAAR_SCALE_IMAGE
,
Size(30, 30) );
for( vector<Rect>::const_iterator nr = nestedObjects.begin(); nr != nestedObjects.end(); nr++ )
{
center.x = cvRound((r->x + nr->x + nr->width*0.5)*scale);
center.y = cvRound((r->y + nr->y + nr->height*0.5)*scale);
radius = cvRound((nr->width + nr->height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
}
cv::imshow( "result", img );
}
Need some help how to resolve it...
The access violation error probably means you are accessing a pointer that you haven't set the value for.
If you don't understand how to use the debugger (learn!) put printf("ok1,2,3 ....\n"); liberally through the code and work out how far it's gettign so you can narrow down where the error happens
I got this error too with OpenCV 2.3 on VS2010, even after adjusting the code so that cascadeName uses the full path to haarcascade_frontalface_alt.xml.
I was able to pinpoint the problem to the line that crashes the application:
if( !cascade.load( cascadeName ) )
The crash is coming from OpenCV's code and I don't know why it happens.

Resources