I got this indicator for mt4, I would like somebody to help me modify it so I can input an integer to select how many bars should be plotted. normally it will plot infinite bars, I'd like to be able to select the number of MTF bars the indicator should plot. This to eliminate the lag when changin timeframes, I imagine the lag is because of the big amount of MTF candles plotted.
Other change that I would really apreciate, if you see when open and close price is exactly the same it will not create a doji, it will only show wicks, not the classic horizontal line for a doji.
I paid a coder to make this, now he's chargin plus to make this changes, I tried to make them myself copying an indicator that has that function but my coding skills are hugely limited.
Thanks.
//+------------------------------------------------------------------+
//| MTF_Candles.mq4 |
//+------------------------------------------------------------------+
#property copyright "Ab Moncada"
#property version "1.0"
#property strict
#property indicator_chart_window
enum enumTimeFrames{
m1 = PERIOD_M1, //M1
m5 = PERIOD_M5, //M5
m15 = PERIOD_M15, //M15
m30 = PERIOD_M30, //M30
h1 = PERIOD_H1, //H1
h4 = PERIOD_H4, //H4
d1 = PERIOD_D1, //D1
w1 = PERIOD_W1, //W1
mn1 = PERIOD_MN1 //MN1
};
//input ENUM_TIMEFRAMES MTF_Period = PERIOD_H1; //Timeframe
input enumTimeFrames MTF_Period = h1; //Timeframe
input color UpColor = clrGainsboro; //ColorBulls
input color DownColor = clrGainsboro; //ColorBears
input bool LineType = false; //Background
input ENUM_LINE_STYLE LineStyle = STYLE_DOT; //LineStyle
input int LineWidth = 3; //LineWidth
string indiName = "MTF_CandleStick";
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit(){
//--- indicator buffers mapping
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){
objDelete(indiName+IntegerToString(MTF_Period));
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(MTF_Period <= _Period) return(0);
int limit = rates_total - prev_calculated;
if(limit > 0){
objDelete(indiName+IntegerToString(MTF_Period));
limit = rates_total-1;
}
else{
if(MTF_Period < 1440) limit = MTF_Period/_Period;
else limit = 1;
}
for(int i=0; i<limit; i++){
double mtfOpen, mtfClose, mtfHigh, mtfLow;
int first, last=0;
if(MTF_Period < 1440){
if(MathMod(time[i], MTF_Period*60) != 0) continue;
first = i;
for(int t=i-1; t>=0; t--){
if(time[i]+MTF_Period*60 <= time[t]){
last = t+1;
break;
}
}
mtfOpen = open[first];
mtfClose = close[last];
mtfHigh = high[iHighest(NULL, 0, MODE_HIGH, first-last+1, last)];
mtfLow = low[iLowest(NULL, 0, MODE_LOW, first-last+1, last)];
}
else{
if(time[Bars-1] > iTime(NULL, MTF_Period, i)) break;
mtfOpen = iOpen(NULL, MTF_Period, i);
mtfClose = iClose(NULL, MTF_Period, i);
mtfHigh = iHigh(NULL, MTF_Period, i);
mtfLow = iLow(NULL, MTF_Period, i);
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false);
if(TimeHour(time[first]) != 0) first--;
if(i > 0){
last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false);
if(TimeHour(time[last]) == 0) last++;
}
/*
if(MTF_Period == 1440){
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false);
if(i > 0) last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false)+1;
}
else{
first = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i), false)-1;
if(i > 0) last = iBarShift(NULL, 0, iTime(NULL, MTF_Period, i-1), false);
}
*/
}
if(mtfOpen <= mtfClose){
Rectangle(indiName+IntegerToString(MTF_Period)+"_body"+IntegerToString(i), first, mtfOpen, last, mtfClose, UpColor, LineStyle, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_shadow"+IntegerToString(i), (first+last)/2, mtfClose, mtfHigh, UpColor, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_tail"+IntegerToString(i), (first+last)/2, mtfOpen, mtfLow, UpColor, LineWidth);
}
else{
Rectangle(indiName+IntegerToString(MTF_Period)+"_body"+IntegerToString(i), first, mtfOpen, last, mtfClose, DownColor, LineStyle, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_shadow"+IntegerToString(i), (first+last)/2, mtfOpen, mtfHigh, DownColor, LineWidth);
TrendLine(indiName+IntegerToString(MTF_Period)+"_tail"+IntegerToString(i), (first+last)/2, mtfClose, mtfLow, DownColor, LineWidth);
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
void Rectangle(string name, int index1, double price1, int index2, double price2, color Rcolor, int Rstyle, int Rwidth){
long id = ChartID();
if (ObjectFind(name) != 0) {
ObjectCreate(id, name, OBJ_RECTANGLE, 0, Time[index1], price1, Time[index2], price2);
ObjectSetInteger(id, name, OBJPROP_COLOR, Rcolor);
if(LineType) ObjectSetInteger(id, name, OBJPROP_STYLE, Rstyle);
ObjectSetInteger(id, name, OBJPROP_WIDTH, Rwidth);
ObjectSetInteger(id, name, OBJPROP_BACK, !LineType);
//ObjectSetInteger(id, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(id, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(id, name, OBJPROP_HIDDEN, true);
}
else{
ObjectMove(name, 0, Time[index1], price1);
ObjectMove(name, 1, Time[index2], price2);
}
ChartRedraw(id);
}
void TrendLine(string name, int position, double price1, double price2, color Tcolor, int Twidth){
long id = ChartID();
if (ObjectFind(name) != 0) {
ObjectCreate(id, name, OBJ_TREND, 0, Time[position], price1, Time[position], price2);
ObjectSetInteger(id, name, OBJPROP_COLOR, Tcolor);
ObjectSetInteger(id, name, OBJPROP_STYLE, STYLE_SOLID);
ObjectSetInteger(id, name, OBJPROP_WIDTH, Twidth);
ObjectSetInteger(id, name, OBJPROP_BACK, true);
ObjectSetInteger(id, name, OBJPROP_RAY_RIGHT, false);
ObjectSetInteger(id, name, OBJPROP_SELECTABLE, false);
ObjectSetInteger(id, name, OBJPROP_HIDDEN, true);
}
else{
ObjectMove(name, 0, Time[position], price1);
ObjectMove(name, 1, Time[position], price2);
}
ChartRedraw(id);
}
void objDelete(string basicName){
for(int i=ObjectsTotal();i>=0;i--){
string ObjName = ObjectName(i);
if(StringFind(ObjName, basicName) >=0) ObjectDelete(ObjName);
}
}
Related
i have a small expert with mql4 for forex robot
but i have get some problem in getting code when running this code to backtest in metatrader 4
my code details is :
i have 2 ema and when cross up get buy and when cross down get sell
but its problem to get position after crosing 2 ema in backtest.
My stoplose is fix to 10 pip but tp is 0 and we have open trade until next cross from 2 ema and then close pervios position and get new position.
i add test sterategy and show my problem in getting position
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input double StopLoss = 100;
input double TakeProfit = 0;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
BuyCondition = False;
GetBuy();
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderClosePrice(), Slippage, clrWhite );
}
SellCondition = False;
GetSell();
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
int GetBuy(){
int getposition = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
return True;
}
int GetSell(){
int getposition = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),0,"Sell",MagicNumber,0,Red);
return True;
}
enter image description here
I edited your code. The main problem in your code is takeprofit!
In GetBuy() and GetSell() Functions you wrote:
Ask+(TakeProfit*Point)
It returns Ask! because your TakeProfit has been set to zero. If you don't want to set Takeprofit You should write:
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),0,"Buy",MagicNumber,0,Blue);
This is the new code:
#property copyright "Copyright 2018"
#property link "https://www.mql4.com"
#property version "1.00"
#property strict
input int Ema_Fast_Period = 62;
input int Ema_Slow_Period = 30;
input int MagicNumber = 1982;
input double Lots = 0.01;
input int StopLoss = 100;
input int TakeProfit = 1000;
double FastMACurrent ,SlowMACurrent ,FastMAPrevious ,SlowMAPrevious;
bool BuyCondition = False, SellCondition = False, CrossPriseWithFastMAUpShado = False, CrossPriseWithFastMADownShado = False;
//---
int Slippage=5;
double OpenPosition = 0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| expert OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(Volume[0]<=1)
{
FastMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
SlowMACurrent = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,1 );
FastMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Fast_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
SlowMAPrevious = iMA(Symbol() ,PERIOD_CURRENT ,Ema_Slow_Period ,0 ,MODE_EMA ,PRICE_CLOSE ,2 );
//----------------------- BUY CONDITION
BuyCondition = (FastMAPrevious<SlowMAPrevious && FastMACurrent>SlowMACurrent);
//----------------------- SELL CONDITION
SellCondition = (FastMAPrevious>SlowMAPrevious && FastMACurrent<SlowMACurrent);
CrossPriseWithFastMADownShado = ( Low[1]<FastMACurrent && FastMACurrent<Open[1] );
if( BuyCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_SELL ? Ask : Bid, Slippage, clrWhite );
}
if(GetBuy()) BuyCondition = False;
}
if( SellCondition )
{
//If we have open trade before get another trade close perivios trade and save money
if( OrderSelect(0, SELECT_BY_POS,MODE_TRADES) )
{
int a = OrderClose( OrderTicket(),OrderLots(),OrderType()==OP_BUY ? Bid : Ask, Slippage, clrWhite );
}
if(GetSell()) SellCondition = False;
}
}
}
//+------------------------------------------------------------------+
//| expert Buy Or Sell function |
//+------------------------------------------------------------------+
bool GetBuy(){
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(StopLoss*Point),Ask+ (TakeProfit*Point),"Buy",MagicNumber,0,Blue);
if(ticket > 0) return true;
return false;
}
bool GetSell(){
int ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(StopLoss*Point),Bid- (TakeProfit*Point),"Sell",MagicNumber,0,Red);
if(ticket > 0) return true;
return false;
}
This is my code trying to generate the ADC Cloud indicator.
At first, it can work if I just generate the cloud.
Currently, I am trying to make the histogram green when it is above zero, otherwise red. Then, I separate the Could array into two buffers, GreenBuffer and RedBuffer. At this step, I stuck in an unknown error.
I can make sure the problem is coming from the ERROR PART, marked by Sharp Sign in Code.
Thank you first!
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period=14;
double Cloud[];
double GreenBuffer[];
double RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
//SetIndexBuffer(0, GreenBuffer);
SetIndexBuffer(0, Cloud);
SetIndexLabel(0, "Cloud");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
//SetIndexBuffer(1, Cloud);
//SetIndexStyle(1, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int Limit_calc = 0;
int BarCnt = IndicatorCounted();
Limit_calc = Bars - BarCnt;
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
Cloud[i] = output;
// #########################################
// ###### Error Part #######################
//if (output > 0)
// {
// GreenBuffer[i] = output;
// RedBuffer[i] = 0.00;
// }
//else
// {
// GreenBuffer[i] = 0.00;
// RedBuffer[i] = output;
// }
// ##########################################
}
//Comment(Cloud[1]);
//--- return value of prev_calculated for next call
return(rates_total);
}
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0, GreenBuffer);
SetIndexLabel(0, "Green");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrGreen);
SetIndexBuffer(0, RedBuffer);
SetIndexLabel(0, "Red");
SetIndexStyle(0, DRAW_HISTOGRAM, 0, 2, clrRed);
//---
return(INIT_SUCCEEDED);
}
int OnCalculate( *** )
{
...
for (int i = Limit_calc-1; i >= 0 ; i--)
{
double output = iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i)
- iADX(NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i);
if (output > 0)
{
GreenBuffer[i] = output;
RedBuffer[i] = 0.00;
}
else
{
GreenBuffer[i] = 0.00;
RedBuffer[i] = output;
}
}
...
}
REPAIRED & [PASS]-on-TESTED CODE :
#property strict
#property indicator_separate_window
#property indicator_buffers 2
//--- input parameters
input int ADX_period = 14;
double GreenBuffer[],
RedBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer( 0, GreenBuffer );
SetIndexLabel( 0, "Green" );
SetIndexStyle( 0, DRAW_HISTOGRAM, 0, 2, clrGreen );
SetIndexBuffer( 1, RedBuffer );
SetIndexLabel( 1, "Red" );
SetIndexStyle( 1, DRAW_HISTOGRAM, 0, 2, clrRed );
//---
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate( const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
)
{
//---
int BarCnt = IndicatorCounted();
int Limit_calc = Bars - BarCnt;
for ( int i = Limit_calc - 1; i >= 0 ; i-- )
{
double output = iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_PLUSDI, i )
- iADX( NULL, 0, ADX_period, PRICE_CLOSE, MODE_MINUSDI, i );
if ( output > 0 ) { GreenBuffer[i] = output; RedBuffer[i] = 0.00; }
else { GreenBuffer[i] = 0.00; RedBuffer[i] = output; }
}
//---
return( rates_total );
}
I'm trying to build a first EA, code below, but it doesn't execute any trades.
I know it is very simple, but logically, I think this should Buy and Sell.
I'm trying to only use a code that I understand.
I'd appreciate it if anyone had any feedback!
//
extern int sma_short = 10;
extern int sma_long = 20;
extern double fakeout = 0.0005 ;
extern double stoploss = 150;
extern double risk = 1;
extern int slippage = 5;
extern int magicnumber = 12345;
extern bool SignalMail = false;
extern bool UseTrailingStop = true;
extern int TrailingStop = 150;
double sma_short_t3;
double sma_short_t0;
double sma_long_t3;
double sma_long_t0;
double sma_diff_t3;
double sma_diff_t0;
double lots;
double stoplosslevel;
int P = 1;
int ticket, ticket2;
int total = OrdersTotal();
bool OpenLong = false;
bool OpenShort = false;
bool CloseLong = false;
bool CloseShort = false;
bool isYenPair = false;
bool OpenOrder = false;
int OnInit()
{
if ( Digits == 5 || Digits == 3 || Digits == 1 ) P = 10; else P = 1; // To account for 5 digit brokers
if ( Digits == 3 || Digits == 2 ) isYenPair = true; // Adjust for YenPair
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit( const int reason )
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void Start()
{
sma_short_t3 = iMA( NULL, 0, sma_short, 0, MODE_SMA, PRICE_CLOSE, 3 );
sma_short_t0 = iMA( NULL, 0, sma_short, 0, MODE_SMA, PRICE_CLOSE, 0 );
sma_long_t3 = iMA( NULL, 0, sma_long, 0, MODE_SMA, PRICE_CLOSE, 3 );
sma_long_t0 = iMA( NULL, 0, sma_long, 0, MODE_SMA, PRICE_CLOSE, 0 );
sma_diff_t3 = sma_long_t3 - sma_short_t3;
sma_diff_t0 = sma_long_t0 - sma_short_t0;
if ( OpenOrder )
{
if ( CloseLong || CloseShort )
{
OrderClose( OrderTicket(), OrderLots(), Bid, slippage, MediumSeaGreen );
OpenOrder = False;
CloseLong = False;
CloseShort = False;
}
}
if ( sma_diff_t3 < 0 && sma_diff_t0 > fakeout )
{
OpenLong = True ;
CloseShort = True;
}
if ( sma_diff_t3 > 0 && sma_diff_t0 < -fakeout )
{
OpenShort = True;
CloseLong = True;
}
lots = risk * 0.01 * AccountBalance() / ( MarketInfo( Symbol(), MODE_LOTSIZE ) * stoploss * P * Point ); // Sizing Algo based on account size
if ( isYenPair == true ) lots = lots * 100; // Adjust for Yen Pairs
lots = NormalizeDouble( lots, 2 );
if ( OpenLong )
{
stoplosslevel = Ask - stoploss * Point * P;
OrderSend( Symbol(), OP_BUY, lots, Ask, slippage, stoplosslevel, 0, "Buy(#" + magicnumber + ")", magicnumber, 0, DodgerBlue );
OpenOrder = True;
}
if ( OpenShort )
{
stoplosslevel = Bid + stoploss * Point * P;
OrderSend( Symbol(), OP_SELL, lots, Ask, slippage, stoplosslevel, 0, "Buy(#" + magicnumber + ")", magicnumber, 0, DodgerBlue );
OpenOrder = True ;
}
}
//+------------------------------------------------------------------+
and why do you use (MarketInfo(Symbol(),MODE_LOTSIZE)? what is the idea of that? first try with double lots = 1.00; and if problem still exists - please add a line telling about the reason why ea failed to send. sth like int ticket = OrderSend(***); if(ticket<0)Print("error=",GetLastError()); or more complex telling about the actual prices, lots, stoploss etc.
Few things in MQL4 to rather get used to:
All PriceDOMAIN data has to be NormalizeDouble() before sending to MetaTrader 4 Server.
All EquityDOMAIN data has to follow a set of discrete values,having MathMin( aMinLOT_SIZE + N * aMinLOT_STEP, aMaxLOT_SIZE ). Normalisation of EquityDOMAIN data is broker-specificand instrument-specific, so need not be always 2.
For XTO, OrderSend(), OrderMOdify(), OrderClose(), one ought follow something like this:
if ( OpenLong )
{ stoplosslevel = NormalizeDouble( Ask - stoploss * Point * P, _Digits ); // ALWAYS NormalizeDouble()
int RetCODE = OrderSend( _Symbol,
OP_BUY,
lots,
Ask,
slippage,
stoplosslevel,
0,
"Buy(#" + magicnumber + ")",
magicnumber,
0,
DodgerBlue
);
if ( RetCODE < 0 )
{ Print( "EXC: Tried to go LONG, OrderSend() failed to get confirmed ( Errno: ", GetLastError(), " )" );
}
else
{ OpenOrder = True;
...
}
...
}
I have some code to draw a line between two points on an image which are selected by mouse, and then to display a histogram.
However, when I press q as required by code I get an error saying R6010 abort() has been called and saying VC++ run time error.
Please advise me how I can find this error.
#include <vector>
#include "opencv2/highgui/highgui.hpp"
#include <opencv\cv.h>
#include <iostream>
#include<conio.h>
using namespace cv;
using namespace std;
struct Data_point
{
int x;
unsigned short int y;
};
int PlotMeNow(unsigned short int *values, unsigned int nSamples)
{
std::vector<Data_point> graph(nSamples);
for (unsigned int i = 0; i < nSamples; i++)
{
graph[i].x = i;
graph[i].y = values[i];
}
cv::Size imageSize(5000, 500); // your window size
cv::Mat image(imageSize, CV_8UC1);
if (image.empty()) //check whether the image is valid or not
{
std::cout << "Error : Image cannot be created..!!" << std::endl;
system("pause"); //wait for a key press
return 0;
}
else
{
std::cout << "Good job : Image created successfully..!!" << std::endl;
}
// tru to do some ofesseting so the graph do not hide on x or y axis
Data_point dataOffset;
dataOffset.x = 20;
// we have to mirror the y axis!
dataOffset.y = 5000;
for (unsigned int i = 0; i<nSamples; ++i)
{
graph[i].x = (graph[i].x + dataOffset.x) * 3;
graph[i].y = (graph[i].y + dataOffset.y) / 200;
}
// draw the samples
for (unsigned int i = 0; i<nSamples - 1; ++i)
{
cv::Point2f p1;
p1.x = graph[i].x;
p1.y = graph[i].y;
cv::Point2f p2;
p2.x = graph[i + 1].x;
p2.y = graph[i + 1].y;
cv::line(image, p1, p2, 'r', 1, 4, 0);
}
cv::namedWindow("MyWindow1", CV_WINDOW_AUTOSIZE); //create a window with the name "MyWindow"
cv::imshow("MyWindow1", image); //display the image which is stored in the 'img' in the "MyWindow" window
while (true)
{
char c = cv::waitKey(10);
if (c == 'q')
break;
}
destroyWindow("MyWindow1");
destroyWindow("MyWindow"); //destroy the window with the name, "MyWindow"
return 0;
}
void IterateLine(const Mat& image, vector<ushort>& linePixels, Point p2, Point p1, int* count1)
{
LineIterator it(image, p2, p1, 8);
for (int i = 0; i < it.count; i++, it++)
{
linePixels.push_back(image.at<ushort>(it.pos())); //doubt
}
*count1 = it.count;
}
//working line with mouse
void onMouse(int evt, int x, int y, int flags, void* param)
{
if (evt == CV_EVENT_LBUTTONDOWN)
{
std::vector<cv::Point>* ptPtr = (std::vector<cv::Point>*)param;
ptPtr->push_back(cv::Point(x, y));
}
}
void drawline(Mat image, std::vector<Point>& points)
{
cv::namedWindow("Output Window");
cv::setMouseCallback("Output Window", onMouse, (void*)&points);
int X1 = 0, Y1 = 0, X2 = 0, Y2 = 0;
while (1)
{
cv::imshow("Output Window", image);
if (points.size() > 1) //we have 2 points
{
for (auto it = points.begin(); it != points.end(); ++it)
{
}
break;
}
waitKey(10);
}
//just for testing that we are getting pixel values
X1 = points[0].x;
X2 = points[1].x;
Y1 = points[0].y;
Y2 = points[1].y;
// Draw a line
line(image, Point(X1, Y1), Point(X2, Y2), 'r', 2, 8);
cv::imshow("Output Window", image);
//exit image window
while (true)
{
char c = cv::waitKey(10);
if (c == 'q')
break;
}
destroyWindow("Output Window");
}
void show_histogram_image(Mat img1)
{
int sbins = 65536;
int histSize[] = { sbins };
float sranges[] = { 0, 65536 };
const float* ranges[] = { sranges };
cv::MatND hist;
int channels[] = { 0 };
cv::calcHist(&img1, 1, channels, cv::Mat(), // do not use mask
hist, 1, histSize, ranges,
true, // the histogram is uniform
false);
double maxVal = 0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int xscale = 10;
int yscale = 10;
cv::Mat hist_image;
hist_image = cv::Mat::zeros(65536, sbins*xscale, CV_16UC1);
for int s = 0; s < sbins; s++)
{
float binVal = hist.at<float>(s, 0);
int intensity = cvRound(binVal * 65535 / maxVal);
rectangle(hist_image, cv::Point(s*xscale, hist_image.rows),
cv::Point((s + 1)*xscale - 1, hist_image.rows - intensity),
cv::Scalar::all(65535), 1);
}
imshow("Histogram", hist_image);
waitKey(0);
}
int main()
{
vector<Point> points1;
vector<ushort>linePixels;
Mat img = cvLoadImage("desert.jpg");
if (img.empty()) //check whether the image is valid or not
{
cout << "Error : Image cannot be read..!!" << endl;
system("pause"); //wait for a key press
return -1;
}
//Draw the line
drawline(img, points1);
//now check the collected points
Mat img1 = cvLoadImage("desert.jpg");
if (img1.empty()) //check whether the image is valid or not
{
cout << "Error : Image cannot be read..!!" << endl;
system("pause"); //wait for a key press
return -1;
}
int *t = new int;
IterateLine( img1, linePixels, points1[1], points1[0], t );
PlotMeNow(&linePixels[0], t[0]);
show_histogram_image(img);
delete t;
_getch();
return 0;
}
This is one of the bad smells in your code:
void IterateLine(const Mat& image, vector<ushort>& linePixels, Point p2, Point p1, int* count1)
{
...
linePixels.push_back(image.at<ushort>(it.pos())); //doubt
Now image is a CV_8UC3 image (from Mat img1 = cvLoadImage("desert.jpg");, but you are accessing here like it is CV_16UC1, so what gets put in linePixels is garbage. This will almost certainly cause PlotMeNow() to draw outside its image and corrupt something, which is probably why your code is crashing.
Sine it is very unclear what your code is trying to do, I can't suggest what you should have here instead.
I have just managed to do this, you only have to put "-1" to your loop limit:
for (unsigned int i = 0; i < nSamples-1; i++)
{
graph[i].x = i;
graph[i].y = values[i];
}
I want to track objects using the Camshift algorithm. I tried to correct the bugs that I found in the JavaCV translation of the original OpenCV Camshift file.
Here is my code:
package objectTracking;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import static com.googlecode.javacv.cpp.opencv_core.*;
import com.googlecode.javacv.cpp.opencv_core.CvBox2D;
import com.googlecode.javacv.cpp.opencv_core.CvPoint;
import com.googlecode.javacv.cpp.opencv_core.CvRect;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_core.IplImageArray;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import com.googlecode.javacv.cpp.opencv_imgproc.CvConnectedComp;
import com.googlecode.javacv.cpp.opencv_imgproc.CvHistogram;
import static com.googlecode.javacv.cpp.opencv_video.*;
import com.sun.jna.ptr.FloatByReference;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class CamShifter implements MouseListener{
final static int MOUSE_PRESSED = 1;
final static int MOUSE_RELEASED = 2;
IplImage image, frame, hsv, hue, mask, backproject, histimg;
IplImageArray hueArray;
CvHistogram hist;
CanvasFrame histogram = new CanvasFrame("Histogram"), camshiftDemo = new CanvasFrame("CamshiftDemo");
boolean backproject_mode = false;
boolean select_object = false;
int track_object = 0;
boolean show_hist = true;
boolean paused = false;
CvPoint origin = new CvPoint();
CvRect selection = new CvRect();
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
CvRect track_window = new CvRect();
CvBox2D track_box = new CvBox2D();
CvConnectedComp track_comp = new CvConnectedComp();
int hsize = 16;
float hranges[] = {0,180};
int[] hdims = {hsize};
float hranges_arr[][] = {hranges};
int vmin = 10, vmax = 256, smin = 30;
public static void main(String args[]) throws Exception {
CamShifter csh = new CamShifter();
csh.work(csh);
System.out.println("CamShiftDetector trial");
}
public CamShifter() throws FrameGrabber.Exception {
grabber.start();
camshiftDemo.getCanvas().addMouseListener(this);
}
public void onMouse(int event, int x, int y) {
if (select_object) {
//get selection
int selX, selY, selW, selH;
selX = Math.min(x, origin.x());
selY = Math.min(y, origin.y());
selW = selX + Math.abs(x - origin.x());
selH = selY + Math.abs(y - origin.y());
selection = cvRect(selX, selY, selW, selH);
System.out.println("Selection : \n("+selX+", "+selY+")\n("+selW+", "+selH+")");
//ensure that selection is enclosed within the image
selX = Math.max(selection.x(), 0);
selY = Math.max(selection.y(), 0);
selW = Math.min(selection.width(), image.width());
selH = Math.min(selection.height(), image.height());
selection = cvRect(selX, selY, selW - selX, selH - selY);
System.out.println("ensure that selection is enclosed within the image");
System.out.println("Selection : \n("+selX+", "+selY+")\n("+selW+", "+selH+")");
}
switch (event) {
case MOUSE_PRESSED:
origin = cvPoint(x, y);
selection = cvRect(x, y, 0, 0);
select_object = true;
break;
case MOUSE_RELEASED:
select_object = false;
if (selection.width() > 0 && selection.height() > 0) {
track_object = -1;
}
break;
}
}
CvScalar hsv2rgb(float hue) {
int[] rgb = new int[3];
int p, sector;
int[][] sector_data = {{0, 2, 1}, {1, 2, 0}, {1, 0, 2}, {2, 0, 1}, {2, 1, 0}, {0, 1, 2}};
hue *= 0.033333333333333333333333333333333f;
sector = (int) Math.floor(hue);
p = Math.round(255 * (hue - sector));
p = p ^ 1;
int temp = 0;
if ((sector & 1) == 1) {
temp = 255;
} else {
temp = 0;
}
p ^= temp;
rgb[sector_data[sector][0]] = 255;
rgb[sector_data[sector][1]] = 0;
rgb[sector_data[sector][2]] = p;
return cvScalar(rgb[2], rgb[1], rgb[0], 0);
}
String coffee;
public void work(CamShifter csh) throws Exception {
IplImage capture = grabber.grab();
System.out.println("paused = "+paused);
if (capture == null) {
System.out.println("Could not initialize capturing...\n");
return;
}
while (true) {
int bin_w;
if (!paused) {
frame = grabber.grab();
if (frame == null) {
return;
}
}
if (image == null) {
image = cvCreateImage(frame.cvSize(), 8, 3);
hsv = cvCreateImage(frame.cvSize(), 8, 3);
hue = cvCreateImage(frame.cvSize(), 8, 1);
mask = cvCreateImage(frame.cvSize(), 8, 1);
backproject = cvCreateImage(frame.cvSize(), 8, 1);
histimg = cvCreateImage(cvSize(320, 200), 8, 3);
cvZero(histimg);
hist = cvCreateHist( 1, hdims, CV_HIST_ARRAY, hranges_arr, 1 );
}
cvCopy(frame, image);
if (!paused)
{
cvCvtColor(image, hsv, CV_BGR2HSV);
if (track_object != 0) {
int _vmin = vmin, _vmax = vmax;
cvInRangeS(hsv, cvScalar(0, smin, Math.min(_vmin, _vmax), 0), cvScalar(180, 256, Math.max(_vmin, _vmax), 0), mask);
cvSplit(hsv, hue, null, null, null);
hueArray = new IplImageArray(hue);
if (track_object < 0) {
float max_val = 0.f;
cvSetImageROI(hue, selection);
cvSetImageROI(mask, selection);
cvCalcHist(hueArray, hist, 0, null);
if (max_val != 0) { // TODO: entier non null == true en C, à vérifier
max_val = (float) 255. / max_val;
} else {
max_val = 0;
}
FloatByReference fl_ref = new FloatByReference(max_val);
cvConvertScale(hist.bins(), hist.bins(), Float.parseFloat(fl_ref.toString()), 0);
cvResetImageROI(hue);
cvResetImageROI(mask);
track_window = selection;
track_object = 1;
cvZero(histimg);
bin_w = histimg.width() / hsize;
for (int i = 0; i < hsize; i++) {
int val = Math.round((int) (cvGetReal1D(hist.bins(), i) * histimg.height() / 255.));
CvScalar color = hsv2rgb(i * 180.f / hsize);
cvRectangle(histimg, cvPoint(i * bin_w, histimg.height()), cvPoint((i + 1) * bin_w, histimg.height() - val), color, -1, 8, 0);
}
}
cvCalcBackProject(hueArray, backproject, hist);
cvAnd(backproject, mask, backproject, null);
cvCamShift(backproject, track_window, cvTermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1), track_comp, track_box);
track_window = track_comp.rect();
// if (track_window.width()*track_window.height()<=1)
// {
// int cols = backproject.width(), rows = backproject.height(), r = (Math.min(cols, rows)+5)/6;
// track_window = cvRect(
// Math.max(track_window.x()-r,0),
// Math.max(track_window.y()-r,0),
// Math.min(track_window.x()+r,cols),
// Math.min(track_window.y()+r,rows));
// }
if (backproject_mode) {
cvCvtColor(backproject, image, CV_GRAY2BGR);
}
if (image.origin() == 0) {
track_box = track_box.angle(-track_box.angle());
cvEllipseBox(image, track_box, cvScalar(0, 0, 255, 0), 3, CV_AA, 0);
}
}
} else if (track_object < 0) {
paused = false;
}
if (select_object && selection.width() > 0 && selection.height() > 0) {
cvSetImageROI(image, selection);
cvXorS(image, cvScalarAll(255), image, null);
cvResetImageROI(image);
}
camshiftDemo.showImage(image);
histogram.showImage(histimg);
}
}
#Override
public void mouseClicked(MouseEvent e) {
// System.out.println("Mouse Clicked !");
}
#Override
public void mousePressed(MouseEvent e) {
this.onMouse(MOUSE_PRESSED, e.getX(), e.getY());
System.out.println("Mouse Pressed !");
System.out.println("\t e.getX(): "+e.getX());
System.out.println("\t e.getY(): "+e.getY());
}
#Override
public void mouseReleased(MouseEvent e) {
this.onMouse(MOUSE_RELEASED, e.getX(), e.getY());
System.out.println("Mouse Released !");
System.out.println("\t e.getX(): "+e.getX());
System.out.println("\t e.getY(): "+e.getY());
}
#Override
public void mouseEntered(MouseEvent e) {
// System.out.println("Mouse Entered !");
}
#Override
public void mouseExited(MouseEvent e) {
// System.out.println("Mouse Exited !");
}
}
Everytime I run the application, and after I select my object to track, the JVM crashes when getting to the line containing cvCalcHist.
Can anyone please tell me what's wrong with my code. I've been on it since days and I can't figure out the problem with it :(
Thank you very much.