MQL4 How to check if last open position in profit - mql4

I want to create "Expert advisor" which scaling in\pyramiding\snowballing into trend,
(Another winning position is openning after first one already in breakeven)
Im stuck with function which checks if previous LONG\SHORT open position is already profitable
Seems like my current function always return 1,
extern double ProfitForOpenAnother = 30;
double IsLastLongProfitable(string sy="", int op=OP_BUY) {
int LastLongProfitable = 0;
datetime o;
double l=-1;
int i, k=OrdersTotal();
if (sy=="0") sy=Symbol();
for (i=0; i<k; i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol()==sy || sy=="") {
if (OrderType()==OP_BUY) {
if (op<0 || OrderType()==op) {
if (OrderMagicNumber()==Magic) {
if (o<OrderOpenTime()) {
o=OrderOpenTime();
l=OrderProfit();
if(l>ProfitForOpenAnother)
{
LastLongProfitable=1;
}
}
}
}
}
}
}
}
return(LastLongProfitable);
} ```

double profit_buy=0,profit_sell=0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
{
datetime time_order=OrderOpenTime();
double profit_order=OrderProfit()-OrderCommission()+OrderSwap();
if(OrderType()==OP_BUY && time_buy<time_order)
{
time_buy=time_order;
profit_buy=profit_order;
}
if(OrderType()==OP_SELL && time_sell<time_order)
{
time_sell=time_order;
profit_sell=profit_order;
}
}
}```

Related

EA - Multi Currency Multi TimeFrame

I have a problem when I'm trying to find a way to check if a trade was made on the current bar or not to stop the EA for making multiple entries on the same bar.
When I don't do a multi Currency EA I usually just use
static datetime lastTradeBar;
and
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
but this doesn't work when using it as I do now.
I'm thinking I need to make a myArray[sym,period,lastTradeBar] or myArray [sym][period][lastTradeBar]
but I can't wrap my head around how or where to put it.
this is the flow
int OnInit() ->
void OnTimer() ->
void LoopThruSym(stringlistOfSym) ->
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym) ->
void Trade(string sym, int period) ->
int Signal(string sym, int period)
This is how the flow is now.
int OnInit()
{
EventSetTimer(5);
return(INIT_SUCCEEDED);
}
....
void OnTimer()
{
LoopThruSym(symbols);
}
....
void LoopThruSym(string listOfSym)
{
if(Mode == All)
{
int i;
int numSymbolmarketWatch=SymbolsTotal(false);
numSymbols=numSymbolmarketWatch;
ArrayResize(symbolListFinal,numSymbolmarketWatch);
for(i=0; i<numSymbolmarketWatch; i++)
{
symbolListFinal[i]=SymbolName(i,false);
}
}
else
if(Mode == Selected)
{
string sep=",";
ushort u_sep;
int i;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfSym,u_sep,symbolList);
numSymbols=ArraySize(symbolList);
ArrayResize(symbolListFinal,numSymbols);
for(i=0; i<numSymbols; i++)
{
symbolListFinal[i]=symbolPrefix+symbolList[i]+symbolSuffix;
LoopThruPeriod(symbolListFinal[i],periods, numSymbols);
}
}
else
if(Mode == Current)
{
LoopThruPeriod(Symbol(),periods,numSymbols);
}
return;
}
....
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym)
{
if(ModePeriod == All_Period)
{
string periodsALL = "1,5,15,30,60,240,1440,10080,43200";
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(periodsALL,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym+numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
else
if(ModePeriod == Selected_Period)
{
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfPeriods,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym*numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
if(ModePeriod == Current_Period)
{
Trade(sym,Period());
}
}
...
void Trade(string sym, int period)
{
//Print("Symbole = " + sym + " : " + period);
if(OrderMethod == BuyandSell)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
else
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
else
if(OrderMethod == BuyOnly)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
}
else
if(OrderMethod == SellOnly)
{
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
//Trail(sym);
return;
}
...
int Signal(string sym, int period)
{
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
Code a function on the "void OnTick()" like this:
void OnTick()
{
//---
CheckForSignal();
}
And then code the function "CheckForSignal()"
//+------------------------------------------------------------------+
//| Function "CheckForSignal()" |
//+------------------------------------------------------------------+
void CheckForSignal(){
//check here a bar until a Signal given Signal given then initialize it to Time[]
static datetime candletime=0;
if(candletime!=Time[0]){
double upArrow=iCustom(your Custom indicator or whatever parameters);
if(upArrow != EMPTY_VALUE){
EnterTrade(OP_BUY);
}
double downArrow=iCustom(your Custom indicator or whatever parameters);
if(downArrow != EMPTY_VALUE){
EnterTrade(OP_SELL);
}
// if we have a Signal we will initialize candle time to Time[0] to avoid multiple Orders
candletime=Time[0];
}
}
//+------------------------------------------------------------------+
Then Send Signal to Open or Close or whatever you need in my example we will open Trades
//+------------------------------------------------------------------+
//| Function "EnterTrade()" |
//+------------------------------------------------------------------+
void EnterTrade(int type){
int err=0;
double price=0;
double sl=0;
double tp=0;
if(type == OP_BUY){
price=Ask;
}else{
price=Bid;
}
//steppoin8-step15: replace function "OrderSend" parameter
// ->variablename "name" (magic)
//steppoint8-step16: end ";"
int ticket=OrderSend(Symbol(),type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
This is not an answer more of like progress.
So what i'm doing not instead of checking for candletime=Time[0] I check then the last trade close time is for that sym/magic nr and comment. and then runing it thru if(iBarShift(sym,period,OrderCloseTime()) > 1)
this kinda works but I'm getting problems down the road if I'm trying to use symbols with different miniLots. But that will come on another post.
bool getLastOrderClose(string sym, int period)
{
if(OrdersHistoryTotal() == 0)
return true;
string comment = "Multi Currency "+sym+":"+IntegerToString(period);
int count = 0;
int tradesPerSymbole =0;
for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
{
if(OrderSymbol() == sym)
{
if(OrderMagicNumber() == Magic)
{
tradesPerSymbole++;
if(StringFind(comment,OrderComment())<0)
{
if(iBarShift(sym,period,OrderCloseTime()) > 1)
{
return true;
}
}
}
}
}
else
{
Print(sym +" : "+"OrderSend() - getLastOrderClose - error - ", ErrorDescription(GetLastError()));
}
if(tradesPerSymbole == 0)
return true;
return false;
};
//OrderSend('EURUSD',blablabla Parameter)
//OrderSend('GBPUSD',blablabla Parameter)
//OrderSend('USDJPY',blablabla Parameter)
//OrderSend('EURCHF',blablabla Parameter)
int ticket=OrderSend('EURUSD',type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
for(int I=ticket;ticket<Orderstotal();i++){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
I think its not the pro solution but I would declare a Ordersend function for all the pairs where u want to open the order (I need not to say that the order send function should be declared in a conditional so only the the real ordersend be placed)
but the part where I want your attention is you can do it the hardware by declaring the Ordersend(not with Symbol() instead of that with "YourPairname");
hope this help you a little bit to reach your goal gl

XF how to lock focus on entry in iOS?

I have some entries in my app which contain some numbers and I have a button that when I click on the button it adds one unit to the number in the entry that is focused, but the problem is that when i click the button, the entry loses the focus and keyboard disappears, although I want the entry to be focused, I found a solution for Android, but couldn't find anything for iOS!!
Does anybody know what to do? I don't want the entry to lose focus
Update:
private void StepUpButton_Clicked(object sender, EventArgs e)
{
double value;
for (int i = 0; i < 30; i++)
{
if (GetEntries(i).IsFocused)
{
if (String.IsNullOrEmpty(GetEntries(i).Text) || GetEntries(i).Text.Equals("-"))
{
value = 0.00;
}
else
{
value = Convert.ToDouble(GetEntries(i).Text);
}
for (int j = 0; j < 10; j++)
{
if (GetEntries(i) == GetVa1ToVb1Amp(j))
{
GetVa1ToVb1Amp(j).Text = controller.StepUpClicked(0, value).ToString("F2");
}
if (GetEntries(i) == GetIa1ToIb3Amp(j))
{
GetIa1ToIb3Amp(j).Text = controller.StepUpClicked(1, value).ToString("F3");
}
if (GetEntries(i) == GetVa1ToIb3Phase(j))
{
GetVa1ToIb3Phase(j).Text = controller.StepUpClicked(2, value).ToString("F2");
}
if (GetEntries(i) == GetVa1ToIb3Freq(j))
{
GetVa1ToIb3Freq(j).Text = controller.StepUpClicked(3, value).ToString("F3");
}
}
}
}
}

Z sorting multiple nodes in Objective-C

I'm trying to build a game in iOS and am currently using Objective-C. The problem I'm running into is Z-sorting different enemy and player nodes. This is my current code for Z-sorting just one enemy type, and I am only copying this code to z-sort every different type of enemy (Mob). This is leading to ALOT of code that all does essentially the same thing for different objects. The only way I know how to fix this problem is by using template functions, but Objective-C doesn't support that to my knowledge. There has to be a better way...
// If two monsters are standing on the same cell, we need to z sort them based on position
// south-western most body will be closest to the "camera" from players perspective
-(void) zSortMobs {
int i = 0;
int j = 0;
for (i = 0; i < self.maxMobs; i++) {
Mob * mob = [self.mobs objectAtIndex: i];
if (mob.state != 0) {
for (j = 0; j < self.maxMobs; j++) {
Mob * mob2 = [self.mobs objectAtIndex: j];
if (mob2.state != 0) {
if (mob != mob2) {
if (mob.z == mob2.z) {
if (mob.y < mob2.y) {
mob.z++;
}
else if (mob.y == mob2.y) {
if (mob.x < mob2.x) {
mob.z++;
}
else {
mob2.z++;
}
}
else {
mob2.z++;
}
}
}
[mob setZPosition: mob.z];
[mob2 setZPosition: mob2.z];
}
}
for (j = 0; j < self.maxTanks; j++) {
Tank * tank = [self.tanks objectAtIndex: j];
if (tank.state != 0) {
if (mob.z == tank.z) {
if (mob.y < tank.y) {
mob.z++;
}
else if (mob.y == tank.y) {
if (mob.x < tank.x) {
mob.z++;
}
else {
tank.z++;
}
}
else {
tank.z++;
}
}
[mob setZPosition: mob.z];
[tank setZPosition: tank.z];
}
}
if (mob.z == self.gameScene.player.z) {
if (mob.y < self.gameScene.player.y) {
mob.z++;
}
else if (mob.y == self.gameScene.player.y) {
if (mob.x < self.gameScene.player.x) {
mob.z++;
}
else {
self.gameScene.player.z++;
}
}
else {
self.gameScene.player.z++;
}
}
[mob setZPosition: mob.z];
[self.gameScene.player setZPosition: self.gameScene.player.z];
}
}
}

Spoj brackets segment tree

can anyone help me in my code. I am getting WA and m not able to rectify it plzzz
my code http://ideone.com/DkrwIg
problem link : http://www.spoj.com/problems/BRCKTS/
i am a bit doubtful in my modification function.
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
char str[40010];
struct node
{
int sum;
int minsum;
}tree[1000005];
void build(int id,int l,int r)
{
if(r-l<2)
{
if(str[l] == '(')
{
tree[id].sum = 1;
tree[id].minsum = 1;
}
else
{
tree[id].sum = -1;
tree[id].minsum = -1;
}
return;
}
int mid = (r+l)/2;
build(id*2,l,mid);
build(id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
void modify(int index,int id,int l,int r)
{
if(r-l<2)
{
tree[id].sum = tree[id].minsum = -tree[id].sum;
return;
}
int mid = (r+l)/2;
if(index<mid)
modify(index,id*2,l,mid);
else
modify(index,id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
int main()
{
int n,k;
int val;
int h = 1;
for(int h=1;h<=10;h++)
{
scanf("%d",&n);
scanf("%s",str);
build(1,0,n);
//cout<<"Test "<<h<<" :"<<endl;
printf("Test %d:\n",h);
//cin>>k;
scanf("%d",&k);
while(k--)
{
cin>>val;
if(!val)
{
if(tree[1].sum == 0 && tree[1].minsum == 0)
{
//cout<<"YES"<<endl;
printf("YES\n");
}
else
{
//cout<<"NO"<<endl;
printf("NO\n");
}
//cout<<tree[1].sum<<"------------"<<tree[1].minsum<<endl;
}
else
{
modify(val-1,1,0,n);
}
}
}
return 0;
}

Processing with tuio

hi i am new to processing and i'm trying to figure out how to make the sphere move from left to right using a marker instead of the mouse. can you help me please? i can use the marker to shoot but i cant move the sphere by shooting
import TUIO.*;
TuioProcessing tuioClient;
HashMap symbols=new HashMap();
PFont fontA;
int sphereDiameter = 50;
boolean shoot = false;
float obj_size = 60;
int randx()
{
return int(random(600));
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
int[] sphereYCoords = { 0, 0, 0, 0, 0 };
void setup()
{
size(1000,700);
tuioClient = new TuioProcessing(this);
}
void draw()
{
Vector<TuioObject> tuioObjectList =tuioClient.getTuioObjects();
Collections.sort(tuioObjectList, comp);
for (TuioObject tobj:tuioObjectList) {
fill(50, 50, 100);
int id = tobj.getSymbolID();
int x = tobj.getScreenX(width);
int y = tobj.getScreenY(height);
rect(x, y, obj_size, obj_size);
String txt="?";
if (symbols.containsKey(id)) {// if it's one in symbols, then look it up
txt = (String)symbols.get(id);
}
fill(255);
text(txt, x, y);
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
fill(100, 0, 0);
// draw the answer box
// ellipse(answerX, answerY, obj_size, obj_size);
fill(255);
// write the answer text
// text(""+answer, answerX, answerY);
background(1);
fill(color(255,255,0));
stroke(color(0,255,0));
triangle(mouseX-8, 580, mouseX+8, 580, mouseX, 565);
fill(color(255,0,0));
stroke(color(255,0,0));
if(shoot==true)
{
sphereKiller( mouseX);
shoot = false;
}
sphereDropper();
//gameEnder();
}
Comparator<TuioObject> comp = new Comparator<TuioObject>() {
// Comparator object to compare two TuioObjects on the basis of their x position
// Returns -1 if o1 left of o2; 0 if they have same x pos; 1 if o1 right of o2
public int compare(TuioObject o1, TuioObject o2) {
if (o1.getX()<o2.getX()) {
return -1;
}
else if (o1.getX()>o2.getX()) {
return 1;
}
else {
return 0;
}
}
};
void mousePressed()
{
shoot = true;
}
void sphereDropper()
{
stroke(255);
fill(255);
for (int i=0; i<5; i++)
{
ellipse(sphereXCoords[i], sphereYCoords[i]++,
sphereDiameter, sphereDiameter);
}
}
void sphereKiller(int shotX)
{
boolean hit = false;
for (int i = 0; i < 5; i++)
{
if((shotX >= (sphereXCoords[i]-sphereDiameter/2)) &&
(shotX <= (sphereXCoords[i]+sphereDiameter/2)))
{
hit = true;
line(mouseX, 565, mouseX, sphereYCoords[i]);
ellipse(sphereXCoords[i], sphereYCoords[i],
sphereDiameter+25, sphereDiameter+25);
sphereXCoords[i] = randx();
sphereYCoords[i] = 0;
}
}
if(hit == false)
{
line(mouseX, 565, mouseX, 0);
}
}
/* void gameEnder()
{
for (int i=0; i< 5; i++)
{
if(sphereYCoords[i]==600)
{
fill(color(255,0,0));
noLoop();
}
}
}*/
void addTuioObject(TuioObject tobj) {
}
// called when an object is removed from the scene
void removeTuioObject(TuioObject tobj) {
}
/ / called when an object is moved
void updateTuioObject (TuioObject tobj) {
if(tobj.getSymbolID() == 32)
{
shoot = true;
}
}
// called when a cursor is added to the scene
void addTuioCursor(TuioCursor tcur) {
}
// called when a cursor is moved
void updateTuioCursor (TuioCursor tcur) {
}
// called when a cursor is removed from the scene
void removeTuioCursor(TuioCursor tcur) {
}
// called after each message bundle
// representing the end of an image frame
void refresh(TuioTime bundleTime) {
//redraw();
}
What do you mean by "shooting" ?
So you have your tuioClient and you initialize it in setup(). Thats good, because then the callback methods (addTuioObject, removeTuioObject, updateTuioObject, addTuioCursor, updateTuioCursor, removeTuioCursor, refresh) will fire whenever your sketch receives a TUIO message.
Keep in mind that TUIO is based on OSC which is transported over UDP. That means the tracker (reactivision & co) will have to send to the IP and port your sketch is listening to. If both are on the same machine use 127.0.0.1 and port 3333 (default).
Have a look at the examples. You'll find them in the processing "IDE" click:
"File -> Examples"
and Navigate to
"Contributed Libraries -> TUIO"

Resources