How do i calculate all the profit for a certain day? - mql4

double CheckProfitSofar()
{
datetime today = iTime(_Symbol,PERIOD_D1,0);
int dDay=TimeDay(today);
int dMonth = TimeMonth(today);
int dYear = TimeYear(today);
int todayYear, todayMonth, todayDay;
datetime opnOrdTime = 0;
double opnOrdProfit =0;
double addLoss = 0;
for(int s=0 ; s<OrdersHistoryTotal(); s++)
{
if ( OrderSelect( s, SELECT_BY_POS, MODE_HISTORY ) == true )
opnOrdTime = OrderCloseTime();
todayYear=TimeYear(opnOrdTime);
todayMonth =TimeMonth(opnOrdTime);
todayDay=TimeDay(opnOrdTime);
if ( dYear==todayYear && dMonth==todayMonth && dDay==todayDay )
totalLoss_Profit += (OrderProfit() + OrderSwap() + OrderCommission());
}
Comment(dYear," ",dMonth," ",dDay," ",todayYear," ",todayMonth," ",todayDay);
return totalLoss_Profit;
}
What i want to is that i want to calculate the profit (whether +ve or -ve) for a particular day. e.g today. i used the "datetime today" to get the opening time of the first candle of today, then follows. It is not returning the accurate value. Please help out. Thanks in advance.

You just need start of that particular day received by datetime timeStart = iTime(_Symbol,PERIOD_D1,i) and end of that day datetime timeEnd=timeStart+PeriodSeconds(PERIOD_D1);. Then loop over closed deals and filter them out if OrderClosePrice() is not in range.
double getClosedPnlOfDay(const int indexDay)
{
const datetime timeStart=iTime(_Symbol,PERIOD_D1,i),
timeEnd = timeStart+PeriodSeconds(PERIOD_D1);
double result=0.;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))continue;
//filter by OrderSymbol() and OrderMagicNumber() here
if(OrderCloseTime()<timeStart || OrderCloseTime()>=timeEnd) continue;
result+=OrderProfit() + OrderCommission() + OrderSwap();
}
}

Related

Is there any arithmetic formula that can test all given numbers are in row, like [ 3 5 4 ]

I m making a card game where 3 random numbers are generated..I need to check are these numbers Row numbers...
like 4 6 5 and 23,24,22. are row numbers
I have made method but I think there should be easy arithmetic formulas
I have tried this and working well, but I need simple arithmatic formula to avoid use of array and for
bool isAllInRow(int num1, int num2,int num3)
{
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
for(int x=0;x<numbers.length-1;x++)
{
if(numbers[x]-numbers[x+1]!=-1)
{
is_in_row=false;
break;
}
}
return is_in_row;
}
So you want to know if the cards form a straight, with aces both low and high.
Is the "three cards" fixed, or would you want to generalize to more cards?
Sorting should be cheap for such a short list, so that's definitely a good start. Then you just need to check the resulting sequence is increasing adjacent values.
I'd do it as:
bool isStraight(List<int> cards) {
var n = cards.length;
if (n < 2) return true;
cards.sort();
var first = cards.first;
if (first == 1 && cards[1] != 2) {
// Pretend Ace is Jack if n == 3.
// Accepts if remaining cards form a straight up to the King.
first = 14 - n;
}
for (var i = 1; i < n; i++) {
if (cards[i] != first + i) return false;
}
return true;
}
This code rejects card sets that have duplicates, or do not form a straight.
I think you are looking for Arithmetic Progression.
bool checkForAP(List<int> numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
if (numberArr[2] - numberArr[1] != diff) {
return false;
}
return true;
}
And modify your function like
bool isAllInRow(int num1, int num2,int num3) {
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
return checkForAP(numbers);
}
Note: remove sort in AP method as it is of no use. Since your numbers
list length is 3 I directly compared numbers for AP, the same can also
be written for n numbers with for.
bool checkForAp(numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
for(int i = 2; i< numberArr.length ;i++) {
if (numberArr[i] - numberArr[i - 1] != diff) {
return false;
}
}
return true;
}
You could do it like this:
bool isAllInRow(int num1, int num2,int num3) {
if (num1 == num2 || num2 == num3) return false;
var maxNum = max(num1, max(num2, num3));
var minNum = min(num1, min(num2, num3));
return (maxNum - minNum == 2) || (minNum == 1 && maxNum == 13 && num1 + num2 + num3 == 26);
}

Why Buy order is not placed when calculated Stoploss and Take profit are used

I have a simple BUY order that, when the Take Profit and Stoploss are in points (ie: Ask+10*_Point), operates correctly. But when I change the take profit and stop loss from points to my own calculated values (CL_OP), the BUY order is not placing trades. How can I solve the issue:
input int _Hour =16;
input int _Minute =30;
bool NewBar()
{
static datetime OldTime = 0;
if(OldTime < Time[0])
{
OldTime = Time[0];
return(true);
}
else
{
return(false);
}
}
void OnTick()
{
int Hour_Int = Hour();
int Minute_Int = Minute();
double CL_OP = (Close[1] - Open[1]);
bool LastBearHiLoEngulf = (Close[1] < Open[1] && High[1] > High[2] && Low[1] < Low[2] );
if(NewBar())
if(OrdersTotal()==0)
// Apply signals on Buy opportunities
if( Hour_Int == _Hour && Minute_Int == _Minute && LastBearHiLoEngulf == TRUE)
{
int buyticket = OrderSend
(
Symbol(), // all symbols
OP_BUY, // Buy without delay
1, // 1 Microlots
Ask, // for market price
3, // 3 pips slippage
Ask - CL_OP, // Stop Loss - 1000*_Point
Ask + CL_OP , // Take profitworks with 100*_Point
"Buy LastBearHiLoEngulf Target: ", // comment
144, // Magic number
0, // no experiation day
Green // draw green arrow
);
}
}
double CL_OP = (Close[1] - Open[1]);
CL_OP is not a normal price to open trade. Actually, it is the Size of the Candle 1!
It should be something like this:
double CL_OP = Close[1] + (Close[1] - Open[1]);

Can't retrieve data when two or more trades either open or close simultaneously

I have these functions to select the last opened order and the last closed order to retrieve multiple data points. This works, however if one or more orders open simultaneously or close simultaneously, it only picks up one order.
Find Last Opened Order
datetime LastOrderOpenTime = 0;
void SelectMostRecentOpened(int magic_number)
{
for(int i=OrdersHistoryTotal();i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_TICKET,MODE_HISTORY)
&& OrderSymbol()==_Symbol
&& OrderMagicNumber() == magic_number
&& OrderOpenTime() > LastOrderOpenTime)
{
...Fill a two dimensional array with data from the selected order
}
LastOrderOpenTime = OrderOpenTime();
}
}
Find Last Closed Order
datetime LastOrderCloseTime = 0;
void SelectMostRecentClosed(int magic_number)
{
for(int i=OrdersHistoryTotal();i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_TICKET,MODE_HISTORY)
&& OrderSymbol()==_Symbol
&& OrderMagicNumber() == magic_number
&& OrderCloseTime() > LastOrderCloseTime)
{
for(int x = ARRAYSIZE - 1; x>=0 ; x--)
{
double OrderTICKET = OrderTicket();
if(OrderTICKET == Prev_OrderTicket) continue;
if(OrderTICKET == Array_Orders[x, Arr_orderTICKET])
{
...Add data retrieved at orderclose to the same dataslot in the array
based off OrderTicket() to retrieve at a later date. i.e OrderOpenTime(),
OrderProfit() etc.
}
Prev_OrderTicket = OrderTicket();
LastOrderCloseTime = OrderCloseTime();
}
}
}
Each Magic Number per trade is different but still I cannot pick up more than one trade at a time. Any help would be appreciated.

how to track take profit and stoploss in mql4

I have the following code in mql4 and it is partially working but having an issue with order tracking.
int ticket;
void OnTick(){
... not included code, setting variables, etc ...
if(tenkan_sen < kijun_sen){
comment += "\nSHORT!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_BUY){
if(OrderClose(OrderTicket(),OrderLots(),Bid,1000,clrCrimson)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and takeprofit prices
double short_tp = current_close - (atr*6);
double short_sl = current_close + (atr*2);
ticket = OrderSend(_Symbol,OP_SELL,0.01,Bid,1000,short_sl,short_tp,"This is a sell",1,0,clrPink);
}
} else if(tenkan_sen > kijun_sen){
comment += "\nLONG!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_SELL){
if(OrderClose(OrderTicket(),OrderLots(),Ask,1000,clrPink)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and take profit prices
double long_tp = current_close + (atr*6);
double long_sl = current_close - (atr*2);
ticket = OrderSend(_Symbol,OP_BUY,0.01,Ask,1000,long_sl,long_tp,"This is a buy",1,0,clrCrimson);
}
}
}
This was previously based on the logic of closing the previous position upon opening the last position, it was working as expected before I added the sl and tp values. I am not sure how I should reset the ticket variable to 0 in the event of a sl or tp, or if there is a different way I should be handling this.

linkedList insertionsort

This is my implementation for an insertion sort method using linkedList. I have tried it and it works just fine the only problem that there is an index out of bounds exception caused by the J+1 line. Can anyone tell me how to get around that or how to fix it. Thnx
public static <T extends Comparable <? super T>> void insertionSort2(List<T> portion){
int i = 0;
int j = 0;
T value;
//List <T> sorted = new LinkedList<T>();
// goes through the list
for (i = 1; i < portion.size(); i++) {
// takes each value of the list
value = (T) portion.remove(i);
// the index j takes the value of I and checks the rest of the array
// from the point i
j = i - 1;
while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j+1 , portion.remove(j));//it was j+1
j--;
}
// put the value in the correct location.
portion.add(j + 1, value);
}
}
check this code out
just put it as a function in a class and try to call it
void InsertionSort()
{
int temp, out, in;
for(out=1 ; out<size ; out++)
{
temp = list[out];
in = out;
while (in > 0 && list[in-1] > temp)
{
list[in] = list[in-1];
--in;
}
list[in]= temp;
System.out.print("The list in this step became: ");
for (int t=0 ; t<size ; t++)
System.out.print(list[t]+" ");
System.out.println("");
}
}

Resources