EA Opens more orders than expected in MQL4 - mql4

Everything seems fine. But EA usually opens multiple trades in the same second... The way I built it is very linear and i can't seem to spot the logical mistake. It is basically a random martingale EA to test stuff out. Any indicator (that's why I called it random, haven't decided myself) can be put in there.
Basic idea is that it has an upper and lower threshold which determines when it is in buy zone and when at sell zone. Once it is in either zone, if trend goes against it (determined by indicator's value, not symbol's price) it opens another trade with the same SL/TP of the initial order. Also it checks whether initial trade still runs so it does not open other ones and once the initial trade is open. After that the criterias about the rest of the trades (that go against the trade are different).
The problem is that it opens multiple trades at times that it shouldn't, or like 3-4 trades within the same second or two. Any idea why this happens?
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
input int stepValue = 5;
input double lotsize = 0.01;
input int stoploss = 2000;
input int takeprofit = 140;
input int slippage = 10;
input double upper_border = 60.0;
input double lower_border = 40.0;
const string EAComment = "Xind";
string mode = "";
bool first_trade = false;
int InitTicket = 1;
double X = 0.0;
double X_Last = 0.0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
first_trade = false;
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
SearchSignal();
if (mode == "Buy")
{
if (first_trade == false)
{
Buy();
}
if (first_trade == true)
{
MartinCheck();
CloseCheck();
}
}
if (mode == "Sell")
{
if (first_trade == false)
{
Sell();
}
if (first_trade == true)
{
MartinCheck();
CloseCheck();
}
}
}
//+------------------------------------------------------------------+
void Buy()
{
X_Last = X;
first_trade = true;
InitTicket = OrderSend(NULL,OP_BUY,lotsize,Ask,slippage,Ask-stoploss*Point,Ask+takeprofit*Point,EAComment,1,0,clrDarkBlue);
}
//---
void Sell()
{
X_Last = X;
first_trade = true;
InitTicket = OrderSend(NULL,OP_SELL,lotsize,Bid,slippage,Bid+stoploss*Point,Bid-takeprofit*Point,EAComment,1,0,clrDarkRed);
}
//---
void MartinBuy()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET) == true)
{
double new_SL = OrderStopLoss();
double new_TP = OrderTakeProfit();
int dont_care = OrderSend(NULL,OP_BUY,lotsize,Ask,slippage,new_SL,new_TP,EAComment+" martin",1,0,clrDarkBlue);
}
}
//---
void MartinSell()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET) == true)
{
double new_SL = OrderStopLoss();
double new_TP = OrderTakeProfit();
int dont_care = OrderSend(NULL,OP_SELL,lotsize,Bid,slippage,new_SL,new_TP,EAComment+" martin",1,0,clrDarkRed);
}
}
//---
void SearchSignal()
{
X = 0.0; //where 0.0, put here the iCustom for external indicators, or some built-in indicator
if (X >= upper_border)
{
mode = "Sell";
}
else if (X <= lower_border)
{
mode = "Buy";
}
else
{
mode = "";
first_trade = false;
InitTicket = 1;
X_Last = 0.0;
}
}
//---
void CloseCheck()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET))
{
if (OrderCloseTime() == 0)
{
first_trade = true;
}
else if (OrderCloseTime() != 0)
{
first_trade = false;
}
else
{
return;
}
}
}
//---
void MartinCheck()
{
if (mode == "Buy")
{
if ((X_Last - stepValue) >= X)
{
X_Last = X;
MartinBuy();
}
}
if (mode == "Sell")
{
if ((X_Last + stepValue) <= X)
{
X_Last = X;
MartinSell();
}
}
}

The layout of your code makes it possible for several processes to happen in sequence all on the same tick which I assume you do not want. Try changing your code initially to this and work from there:
void OnTick()
{
SearchSignal();
if(mode=="Buy")
{
if(!first_trade) Buy();
else
{
MartinCheck();
CloseCheck();
}
}
else if(mode=="Sell")
{
if(!first_trade) Sell();
else
{
MartinCheck();
CloseCheck();
}
}
}
Remember to use if(...) else to stop executing all functions when it should only be an either/or situation.

Related

Excel mql4 mismatch

This is an indicator I am working on. The problem I am having is it doesn't match the same output as my excel file, and I am pretty sure my excel file is correct. If you would like to help me solve this issue just email me at thetfordjw#gmail.com Subject: Excel mql4 please and I will send you the excel file. Otherwise if you have something to add on this web page as to something I am doing wrong would be happy to hear from you. Thanks !
//+------------------------------------------------------------------+
//| JT-Statistics Close GT LT Terminated.mq4 |
//| Copyright 2021,Jon W. Thetford |
//| Email: thetfordjw#gmail.com |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int i;
float a,b,c,d,e,f,g,h,j,k;
float aa,bb,cc,dd,ee,ff,gg,hh,jj,kk,ll,mm,nn,oo;
//input float BarsBack = "1000";
input bool FrequencyNumber = True;
input bool FrequencyPercentage = False;
input bool CumulativePercentageOfAllBars = False;
//input bool PercentageOfCustomBarsBack = False;
int OnInit()
{
//--- indicator buffers mapping
//---
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[])
{
//---
for(i=0;i<Bars; i++)
{
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]<Close[i+4])
{
a=a+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]<Close[i+5])
{
b=b+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]<Close[i+6])
{
c=c+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]<Close[i+7])
{
d=d+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]<Close[i+8])
{
e=e+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]<Close[i+9])
{
f=f+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]<Close[i+10])
{
g=g+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]<Close[i+11])
{
h=h+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]<Close[i+12])
{
j=j+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]>Close[i+12]&&Close[i+12]<Close[i+13])
{
k=k+1;
}
//LESS THAN Close[1]<Close[2]
//1
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]>Close[i+4])
{
aa=aa+1;
}
//2
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]>Close[i+5])
{
bb=bb+1;
}
//3
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]>Close[i+6])
{
cc=cc+1;
}
//4
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]>Close[i+7])
{
dd=dd+1;
}
//5
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]>Close[i+8])
{
ee=ee+1;
}
//6
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]>Close[i+9])
{
ff=ff+1;
}
//7
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]>Close[i+10])
{
gg=gg+1;
}
//8
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]>Close[i+11])
{
hh=hh+1;
}
//9
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]>Close[i+12])
{
jj=jj+1;
}
//10
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]>Close[i+13])
{
kk=kk+1;
}
//11
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]>Close[i+14])
{
ll=ll+1;
}
//12
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]>Close[i+15])
{
mm=mm+1;
}
//13
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]<Close[i+15]&&Close[i+15]>Close[i+16])
{
nn=nn+1;
}
//=
if(Close[i+1]==Close[i+2])
{
oo=oo+1;
}
//OUTPUT > <
//Frequency NUMBER of consecutive closes greater than and less than the previous.
if(FrequencyNumber) Comment("FrequencyNumber\n# Close[1]>Close[2]\n\n1: "+a+"\n2: "+b+"\n3: "+c+"\n4: "+d+"\n5: "+e+"\n6: "+f+"\n7: "+g+"\n8: "+h+"\n9: "+j+"\n10: "+k
+"\n\n# Close[1]<Close[2]\n\n1: "+aa+"\n2: "+bb+"\n3: "+cc+"\n4: "+dd+"\n5: "+ee+"\n6: "+ff+"\n7: "+gg+"\n8: "+hh+"\n9: "+jj+"\n10: "+kk+"\n11: "+ll+"\n12: "+mm+"\n13: "+nn+"\n==: "+oo+"\n\n Total bars: "+Bars);
}

MQL4 How to call OnChartEvent() from init()

I want to call OnChartEvent() from init() like the code below, so the EA should process first the password and then the rest of the code.
I am just newbie not an expert in coding.
The idea or objective, the password must enter first and correctly, after successful then process the rest of code.
#include <ChartObjects/ChartObjectsTxtControls.mqh>
int init()
{
password_edit.Create(0, "password_edit", 0, 10, 10, 260, 25);
password_edit.BackColor(White);
password_edit.BorderColor(Black);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent( const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//---
if (id == CHARTEVENT_OBJECT_ENDEDIT && sparam == "password_edit" )
{
password_status = -1;
for (int i=0; i<ArraySize(allowed_passwords); i++)
if (password_edit.GetString(OBJPROP_TEXT) == allowed_passwords[i])
{
password_status = i;
break;
}
if (password_status == -1)
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[0]);
ExpertRemove();
}
else
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[1]);
}
}
}
//+------------------------------------------------------------------+
int OnInit(){
passwordOperation();
return INIT_SUCCEED;
}
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
if (id == CHARTEVENT_OBJECT_ENDEDIT && sparam == "password_edit" )
{
passwordOperation();
}
}
void passwordOperation()
{
password_status = -1;
for (int i=0; i<ArraySize(allowed_passwords); i++)
if (password_edit.GetString(OBJPROP_TEXT) == allowed_passwords[i])
{
password_status = i;
break;
}
if (password_status == -1)
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[0]);
ExpertRemove();
}
else
{
password_edit.SetString(OBJPROP_TEXT, 0, password_message[1]);
}
}

MQL4 automatic stop

My Martingale EA should be stopped automatically if the previously manually set limit has been reached or exceeded. The last trade should expire normally and not be interrupted.
So far, I've tried the following code, without interruption, etc. the code works fine.
I also heard about RemoveExpert, but I do not know how to do it. Am grateful for any help :)
enum tradeD{Buy=1, Sell=2};
input tradeD TradeType = Buy;
input double Initial_Lot = 0.01;
input double Lot_Factor = 2;
input int Max_Spread = 30;
input double Pct_SL = 0.1; // Percentage Stop Loss
input double Pct_TP = 0.1; // Percentage Take Profit
input int Magic_Number= 73726;
input int interrupt = 1,0000;
input bool StopEA = false;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
int start()
{
if (StopEA == true) { return(0); } //This line will skip the execution of EA.
}
void OnTick()
{
if(OpenOrders()==0 && (SymbolInfoInteger(Symbol(),SYMBOL_SPREAD)<Max_Spread||Max_Spread==0)){
if(TradeType==Buy){
double flot=Initial_Lot;
double etp=Ask+(Ask*(Pct_TP/100));
etp=NormalizeDouble(etp,Digits);
double esl=Ask-(Ask*(Pct_TP/100));
esl=NormalizeDouble(esl,Digits);
if (ask <= interrupt) { StopEA = true; return(0); }
if(lastProfit()<0){
flot=NormalizeDouble(lastLot()*Lot_Factor,2);
}
int snd=OrderSend(Symbol(),OP_BUY,flot,Ask,10,esl,etp,NULL,Magic_Number,0,clrAliceBlue);
}
if(TradeType==Sell){
double flot=Initial_Lot;
double etp=Bid-(Bid*(Pct_TP/100));
etp=NormalizeDouble(etp,Digits);
double esl=Bid+(Bid*(Pct_TP/100));
esl=NormalizeDouble(esl,Digits);
if (bid >= interrupt) { StopEA = true; return(0); }
if(lastProfit()<0){
flot=NormalizeDouble(lastLot()*Lot_Factor,2);
}
int snd=OrderSend(Symbol(),OP_SELL,flot,Bid,10,esl,etp,NULL,Magic_Number,0,clrAliceBlue);
}
}
//checkProfit();
}
int checkProfit(){
int total=0;
for(int i=OrdersTotal()+5; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
string ordsymB = OrderSymbol();
int ordtypeB =OrderType();
int magicnB = OrderMagicNumber();
int magicn=magicnB;
double ordProfit=OrderProfit();
int tick=OrderTicket();
double oLots=OrderLots();
if(ordsymB==Symbol() && magicnB==Magic_Number){
double pctBalT=AccountBalance()*(Pct_TP/100);
double pctBalS=AccountBalance()*(Pct_SL/100);
if(ordProfit>=pctBalT){
int clo=OrderClose(tick,oLots,Close[0],10,clrAntiqueWhite);
}
if(ordProfit<0 && MathAbs(ordProfit)>=pctBalS){
int clo=OrderClose(tick,oLots,Close[0],10,clrAntiqueWhite);
}
}
}
}
return (total);
}
int OpenOrders(){
int total=0;
for(int i=OrdersTotal()+5; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
string ordsymB = OrderSymbol();
int ordtypeB =OrderType();
int magicnB = OrderMagicNumber();
int magicn=magicnB;
if(ordsymB==Symbol() && magicnB==Magic_Number){
total++;
}
}
}
return (total);
}
double lastProfit(){
double total=0;
datetime lastTime=0;
for(int i=OrdersHistoryTotal(); i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
string ordSym=OrderSymbol();
int ordType=OrderType();
datetime ordTime=OrderOpenTime();
double ordLot=OrderLots();
double ordOp=OrderOpenPrice();
int ordMag=OrderMagicNumber();
double ordProfit=OrderProfit();
if(ordSym==Symbol() && ordTime>lastTime && ordMag==Magic_Number){
lastTime=ordTime;
total=ordProfit;
}
}
}
return(total);
}
double lastLot(){
double total=0;
datetime lastTime=0;
for(int i=OrdersHistoryTotal(); i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
string ordSym=OrderSymbol();
int ordType=OrderType();
datetime ordTime=OrderOpenTime();
double ordLot=OrderLots();
double ordOp=OrderOpenPrice();
int ordMag=OrderMagicNumber();
if(ordSym==Symbol() && ordTime>lastTime && ordMag==Magic_Number){
lastTime=ordTime;
total=ordLot;
}
}
}
return(total);
}
if(tick_counter>=ticks_to_close)
{
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}

How to turn on LED that's attached to an arduino via BLE from ios app?

Here is the scenario. I have an esp32, 2 led's and a ios example app I found online here. Currently If I press a button on my esp32 it notifies the ios app to display "1", if pressed again it displays "0". This works perfectly.
The tricky part is that this ios app allows me to send a write command to the esp32. I'd like to make it so if '1' is sent LED A turns ON and LED B turns OFF, then LED A OFF and LED B ON when 0 is sent. I am unable to do this though. Try as I might I can't figure out where in the chain of this project something is wrong. Maybe the code on the esp32 or maybe the app i'm unsure.
Here is my arduino code. (There is more to the code not mentioned, I actually have 4 led's but I only want to turn on 2 certain ones when a write command is sent).
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
boolean oldState = LOW;
uint32_t value = 0;
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
Serial.print("Received Value: ");
for (int i = 0; i < rxValue.length(); i++) {
Serial.print(rxValue[i]);
}
Serial.println();
if (rxValue.find("1") != -1) {
digitalWrite(13, HIGH);
digitalWrite(27, LOW);
}
else if (rxValue.find("0") != -1) {
digitalWrite(13, LOW);
digitalWrite(27, HIGH);
}
}
}
};
const int bt1 = 14;
boolean bt1g = true;
int bt1t = 0;
void setup() {
pinMode(13, OUTPUT);
pinMode(15, OUTPUT);
pinMode(33, OUTPUT);
pinMode(27, OUTPUT);
pinMode(bt1, INPUT_PULLUP);
Serial.begin(9600);
BLEDevice::init("ESP32");
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY
);
pCharacteristic->addDescriptor(new BLE2902());
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0);
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop()
{
if (bt1g) {
if (digitalRead(bt1) == LOW ) {
bt1t = (bt1t + 1) % 2;
Serial.println(bt1t);
bt1g = false;
}
}
if (!bt1g) {
if (digitalRead(bt1) == HIGH) {
bt1g = true;
}
}
if (bt1t == 0) {
digitalWrite(15, LOW);
digitalWrite(33, HIGH);
}
}
boolean newState = digitalRead(15);
if (deviceConnected) {
if (newState != oldState) {
if (newState == LOW) {
pCharacteristic->setValue("1");
}
else {
pCharacteristic->setValue("0");
}
pCharacteristic->notify();
};
oldState = newState;
}
delay(50);
}
It looks like the entire code for the ios app is too long to submit to this post so here is the github
I'm really unsure and stuck in a rut. Any help is appreciated!
Could it be you are not discovering the correct characteristics? It looks like you only have one service and one characteristic.

How to make Break even trigger more than one time in one entry

I now trying to make Break Even Code trigger more than one time,
example EA entry is 1.28000 and stop loss 1.28500
if current price reach 1.175000(50pips), sl move to break even such as to 1.28000(5pips).
EA will not make more modify order after condition are meet.
so how to trigger break even again if price reach 1.17000(100pips), sl move to (1.175000)(50 pips)
and again price reach 1.165000(150pips),sl move to 1.17000(100pips)
I want to make
BE_B_M(sl move to(example:5))
and
BE_B_T(price reach(example:50))
as variable and every time price reach target variable change to next value
so became
BE_B_M(sl move to(example:50)) and BE_B_T(price reach(example:100))
The entire code is as follows
extern double BE_T_1 = 50;
extern double BE_M_1 = 5;
extern double BE_T_2 = 100;
extern double BE_M_2 = 50;
extern double BE_T_3 = 150;
extern double BE_M_3 = 100;
double BE_S_M;
double BE_S_T;
void MOVE_BE_1()
{
for(int b=OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()==Symbol())
if(OrderType()==OP_BUY)
if(Bid-OrderOpenPrice()>BE_S_T*Pips)
if(OrderOpenPrice()>OrderStopLoss())
if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
Print("eror");
}
for(int s=OrdersTotal()-1;s>=0;s--)
{
if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()==Symbol())
if(OrderType()==OP_SELL)
if(OrderOpenPrice()-Ask>BE_S_T*Pips)
if(OrderOpenPrice()<OrderStopLoss())
if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
Print("eror");
}
}
i expect sl will move after price reach every 50pips from entry
Here you can put all the 3 break even levels on one function.
Note: you can use 1 for-loop for both OP_BUY and OP_SELL
Here is my OnInit()
// Global variable
double point;
int OnInit()
{
if(Digits == 5 || Digits == 3) point=Point*10;
else point=Point;
return(INIT_SUCCEEDED);
}
Here is the BreakEven() function
//+------------------------------------------------------------------+
//| Break even the trade at 3 levels |
//+------------------------------------------------------------------+
void BreakEven()
{
// get the stop level for that symbol
double stopLevel = SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL)*Point;
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()!=Symbol())continue;
if(OrderType()==OP_BUY)
{
double profitPips=Bid-OrderOpenPrice();
double newSL=OrderStopLoss();
if(profitPips>=BE_T_1*point && OrderStopLoss()<OrderOpenPrice()) // Break Even
{
newSL=OrderOpenPrice()+BE_M_1*point;
}
else if(profitPips>=BE_T_3*point) // 150/100
{
newSL=OrderOpenPrice()+BE_M_3*point;
}
else if(profitPips>=BE_T_2*point) // 100/50
{
newSL=OrderOpenPrice()+BE_M_2*point;
}
if(newSL>=OrderStopLoss()+Point && newSL<Bid-stopLevel)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
Print("Error at BE: ",GetLastError());
}
else if(OrderType()==OP_SELL)
{
double profitPips=OrderOpenPrice()-Ask;
double newSL=OrderStopLoss();
if(profitPips>=BE_T_1*point && (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0)) // Break Even
{
newSL=OrderOpenPrice()-BE_M_1*point;
}
else if(profitPips>=BE_T_3*point) // 150/100
{
newSL=OrderOpenPrice()-BE_M_3*point;
}
else if(profitPips>=BE_T_2*point) // 100/50
{
newSL=OrderOpenPrice()-BE_M_2*point;
}
if(newSL<=OrderStopLoss()-Point && newSL>Ask+stopLevel)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
Print("Error at BE: ",GetLastError());
}
}
}
I didn't test this myself in a trade, but it should work.

Resources