How to create a MQL4 function that returns the largest losing trade? [closed] - trading

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create an Expert Adviser (EA) in MQL4 language.
How to code a function that returns the largest losing trade, (and not the total losing trades)?

The following function will return the ticket of the largest loss trade.
With a default of loss = DBL_MAX, this can still return profitable trades with the lowest profit.With a loss = 0, it will only return a trade with the most negative profit or zero.
Will return a ticket of such trade and EMPTY, if no trades found.
int LargestLoss( int magic, double loss = DBL_MAX )
{
int ticket=EMPTY;
for(int i=0; i < Orderstotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderProfit()+OrderSwap()+OrderCommision()<loss)
{
loss=OrderProfit()+OrderSwap()+OrderCommision();
ticket=OrderTicket();
}
}
}
return ticket;
}

An actual Net Profit of any order has 3 components to add:
for a fair comparison, one ought add all [A] + [B] + [C] to compare one against the others:
double aNetLOSS = OrderProfit() // [A]
+ OrderCommission() // [B]
+ OrderSwap(); // [C]
A robust calling-interface ought provide
For a serious MQL4 automation, the returned value ought be always avoding any unwanted side-effects:
bool GetTheTicketWithLargestLOSS( int &aTicket2SEARCH,
double &aValueOfLOSS,
const string aSymbol2SEARCH, // <= _Symbol
const int aMagNUM = 0,
const int aSearchMODE = MODE_TRADES // | MODE_HISTORY
)
{
double aLocalMaxLOSS = 0.;
aTicket2SEARCH = EMPTY; // BLOCK ANY BLIND OrderSelent() USE
for ( int i = 0; i < OrdersTotal(); i++ )
{ // TRY:
if ( OrderSelect( i, SELECT_BY_POS, aSearchMODE ) )
{
if ( OrderSymbol() == aSymbol2SEARCH // MATCH?
&& OrderMagicNumber() == aMagNUM // MATCH?
)
{ double aNetLOSS = OrderProfit() // [A]
+ OrderCommission() // [B]
+ OrderSwap(); // [C]
if ( aNetLOSS < aLocalMaxLOSS )
{
aLocalMaxLOSS = aNetLOSS; // UPDATE
aLocalTkt2FIND = OrderTicket();
}
continue; // ----------------------------^ LOOP NEXT
}
continue; // ----------------------------------^ LOOP NEXT
}
else
{ // ON EXC:
// LOG:
// REPORT:
// HANDLE:
// RET/SIG:
return( False ); // SIG TERM EXIT
}
}
aTicket2SEARCH = aLocalTkt2FIND; // ON FAIR EXIT: FINAL ASSIGNMENTS
aValueOfLOSS = aLocalMaxLOSS;
return( True ); // SIG FAIR EXIT ( &DATA SET )
}

Related

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]);

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.

Why is it that when the second arrow indicator shows up the EA doesn't execute anything?

I've written some code on an Expert Advisor to trade on the Fiji-trend-indicator. The EA recognises the first arrow indicator and executes a trade accordingly, however, when the second arrow is supposed to show up on a back test, the rest of the code doesn't do anything.
I see that the custom price box in the indicator that follows the bid price on the chart stops moving up or down in value when the EA executes the first trade, maybe that's where thing go wrong?
double CloseAllTradesThisPair()
{
for (int i=OrdersTotal();i>=0;i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if (OrderSymbol()==Symbol())
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),10,Red);
}
}
}
extern bool bought = false;
extern bool sold = false;
double Lotsize = AccountBalance()/5000;
double Lots = NormalizeDouble(Lotsize,2);
void OnTick()
{
for(int i=0;i<OrdersTotal();i++)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
return(0);
}
double uparrow = iCustom(Symbol(),PERIOD_CURRENT,"fiji-trend-indicator",2,0);
double dnarrow = iCustom(Symbol(),PERIOD_CURRENT,"fiji-trend-indicator",3,0);
if(uparrow < 1000 && i==0)
{
double buyticket = OrderSend(Symbol(),OP_BUY,0.01,Ask,10,0,0,NULL,0,0,Green);
bought = true;
}
if(dnarrow < 1000 && i==0)
{
double sellticket = OrderSend(Symbol(),OP_SELL,0.01,Bid,10,0,0,NULL,0,0,Red);
sold = true;
}
if(bought != true && dnarrow < 1000 )
{
CloseAllTradesThisPair();
double sticket = OrderSend(Symbol(),OP_SELL,0.01,Bid,10,0,0,NULL,0,0,Red);
}
if(sold != true && uparrow < 1000)
{
CloseAllTradesThisPair();
double bticket = OrderSend(Symbol(),OP_BUY,0.01,Ask,10,0,0,NULL,0,0,Green);
}
}
Q : "when the EA executes the first trade, maybe that's where thing go wrong?"
Oh sure it is.
Given the code, the EA does exactly what it is instructed to in the void OnTick(){...}-code:
...
for ( int i = 0; i < OrdersTotal(); i++ )
{
OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
return( 0 ); // _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _THE_TERMINATOR_ >>> FINITO...
}
...
This fragment does nothing, until a 1st order was placed (as then the i stopped to meet the condition < OrdersTotal().
The rest is obvious: return( 0 ); ...besides a flaw to return a value from void... terminates under no exceptions any and all next code-passes through the OnTick()-code, so effectively avoiding any trading at all:

Getting the max and min price of current chart

After performing
ChartNavigate(0, CHART_END, -5142);
I want to get the max and min price of that particular chart.
I tried
ChartGetDouble(0,CHART_PRICE_MAX,0,top)
ChartGetDouble(0,CHART_PRICE_MIN,0,top)
WindowPriceMax
WindowPriceMin
None of them gives me the price after the ChartNavigate.
What is the right way to do this?
New-MQL4.56789 features may surprise, nevertheless:
Step 0: always catch Chart_OkFLAG
bool Chart_OkFLAG;
double Chart_min,
Chart_MAX;
int Chart_ToBeMODIFIED = ChartID();
int Chart_ToBeMODIFIED_SubWinID = 0;
int Chart_nBarsRelativeSHIFT = 0;
Chart_OkFLAG = ChartNavigate( Chart_ToBeMODIFIED,
< CHART_BEGIN |
CHART_END |
CHART_CURRENT_POS >,
Chart_nBarsRelativeSHIFT
);
If OK: you won the first round, the GUI command has been accepted for being syntactically & context-wise correct. That does not mean, it was executed by the GUI processor. It was just let in, to the tail of the GUI-command-QUEUE.
Step 1: Enforce it's execution ( wise to think about deferring such processing to some safe place, after mission-critical elements have been fulfilled )
if ( Chart_OkFLAG ){
WindowRedraw(); // ol'-MQL4
ChartRedraw( Chart_ToBeMODIFIED ); // new-MQL4
Chart_min = ChartPriceMin( Chart_ToBeMODIFIED,
Chart_ToBeMODIFIED_SubWinID
);
Chart_MAX = ChartPriceMAX( Chart_ToBeMODIFIED,
Chart_ToBeMODIFIED_SubWinID
);
}
else{
// ERROR HANDLING onChartNavigate(T)ERROR
}
ALWAYS: do not hesitate to inline error handlers, even where MQL4 language seems straightforward ( you never know, when that effort pays off by avoiding hours of bug tracking )
double ChartPriceMin( const long Chart_ID = 0,
const int Chart_SubWindow_ID = 0
) {
double result = EMPTY_VALUE;
ResetLastError();
if ( !ChartGetDouble( Chart_ID,
CHART_PRICE_MIN,
Chart_SubWindow_ID,
result
)
){
PrintFormat( "ERROR: Code(%d) in [%s]",
GetLastError(),
__FUNCTION__,
);
}
return( result );
}
double ChartPriceMAX( const long Chart_ID = 0,
const int Chart_SubWindow_ID = 0
) {
double result = EMPTY_VALUE;
ResetLastError();
if ( !ChartGetDouble( Chart_ID,
CHART_PRICE_MAX,
Chart_SubWindow_ID,
result
)
){
PrintFormat( "ERROR: Code(%d) in [%s]",
GetLastError(),
__FUNCTION__,
);
}
return( result );
}

Is there a (JSON or XML) stream parser for nodejs? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
is there a parser for nodejs that can be connected to a a stream of chunked JSON (or XML) data and will emit events similar to how the built in JSON parser does?
The stream I am about to parse is coming from an HTTP request to a backend server for example. No special formatting can be assumed for the incoming JSON. IOW, the solution in nodejs - parsing chunked twitter json won't work for me.
Jan
I don't know if I understood your question, but I have used node-xml before with streamed, chunked data. There are indeed events which are fired. sax-js seems more recently active, but I cannot comment on that project.
I cannot comment on an equivalent JSON parser.
node-xml-splitter could be an answer concerning your xml
streaming needs
jsonpars could be an answer concerning your json
streaming needs
For json, you may use the following snippet.
coffeescript
make_parser = (callback)->
state_parse=0
level=0
buffer=0
parse_out = (data)->
m = data.match /[{}"]/
if m?
c = m[0]
buffer += data[..m.index]
remaining = data[m.index+1..]
if c == "}"
level -= 1
if level == 0
callback JSON.parse(buffer)
init_state()
else if c == "{"
level += 1
else if c == '"'
state_parse = parse_string
state_parse remaining
else
buffer += data
parse_string = (data)->
m = data.match /["\\]/
if m?
c = m[0]
buffer += data[..m.index]
remaining = data[m.index+1..]
transition =
'\\': parse_special
'\"': parse_out
state_parse = transition[c]
state_parse remaining
else
buffer += data
parse_special = (data)->
if data.length > 0
buffer += data[0]
state_parse = parse_string
state_parse data[1..]
init_state =->
state_parse = parse_out
level = 0
buffer = ""
init_state()
(data)->
state_parse data
fs = require "fs"
s = fs.createReadStream "somefile.json"
s.setEncoding 'utf8'
s.on "data", make_parser (d)->
console.log "-----"
console.log d
javascript:
var fs, make_parser, s;
make_parser = function(callback) {
var buffer, init_state, level, parse_out, parse_special, parse_string, state_parse;
state_parse = 0;
level = 0;
buffer = 0;
parse_out = function(data) {
var c, m, remaining;
m = data.match(/[{}"]/);
if (m != null) {
c = m[0];
buffer += data.slice(0, m.index + 1 || 9e9);
remaining = data.slice(m.index + 1);
if (c === "}") {
level -= 1;
if (level === 0) {
callback(JSON.parse(buffer));
init_state();
}
} else if (c === "{") {
level += 1;
} else if (c === '"') {
state_parse = parse_string;
}
return state_parse(remaining);
} else {
return buffer += data;
}
};
parse_string = function(data) {
var c, m, remaining, transition;
m = data.match(/["\\]/);
if (m != null) {
c = m[0];
buffer += data.slice(0, m.index + 1 || 9e9);
remaining = data.slice(m.index + 1);
transition = {
'\\': parse_special,
'\"': parse_out
};
state_parse = transition[c];
return state_parse(remaining);
} else {
return buffer += data;
}
};
parse_special = function(data) {
if (data.length > 0) {
buffer += data[0];
state_parse = parse_string;
return state_parse(data.slice(1));
}
};
init_state = function() {
state_parse = parse_out;
level = 0;
return buffer = "";
};
init_state();
return function(data) {
return state_parse(data);
};
};
fs = require("fs");
s = fs.createReadStream("somefile.json");
s.setEncoding('utf8');
s.on("data", make_parser(function(d) {
console.log("-----");
return console.log(d);
}));

Resources