For MT4,MQL
When sendOrder(),
It sometimes successes or sometimes misses mainly because of slippage.
I would like to get the real slippage when sendOrder().
Is it possible???
My source code for now is like this below.
Ticket = OrderSend(_Symbol,OP_SELL, Lot,Bid,2, // '2' is slippage alloable limit.
SL,TP,comment,Magic);
if (Ticket > 0){
// if slippage is under 2 it works.
// want to check the real slippage
}
else {
int err = GetLastError();
if(err == ERR_NO_ERROR ||
err == ERR_COMMON_ERROR ||
err == ERR_SERVER_BUSY ||
err == ERR_NO_CONNECTION ||
err == ERR_TRADE_TIMEOUT ||
err == ERR_INVALID_PRICE ||
err == ERR_PRICE_CHANGED ||
err == ERR_OFF_QUOTES ||
err == ERR_BROKER_BUSY ||
err == ERR_REQUOTE ||
err == ERR_TRADE_CONTEXT_BUSY){
//want to check the slippage here!!!
}
}
You have to calculate slippage on your own by subtracting the OrderOpenPrice from the price you sent with the order.
Example:
double price = Bid;
double slippage = 0.0;
int ticket = OrderSend(_Symbol, OP_SELL, Lot, price, 2, SL, TP, comment, Magic);
if(OrderSelect(ticket, SELECT_BY_TICKET))
slippage = int(NormalizeDouble(fabs(price - OrderOpenPrice()) / _Point, 0));
Related
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.
I have been trying to implement the shunting yard algorithm, but the output of my parser is incorrect.
let mut stack: Vec<String> = vec![];
let mut op_stack: Vec<String> = vec![];
for current in sub_tree {
if current.tok_type == TokenType::NUMBER || current.tok_type == TokenType::NEGNUMBER {
self.parse();
stack.push(current.content.clone());
}
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
}
The original equation I am parsing: 1 + 2 * 3
I expected the following output: 1 2 3 * +
Instead I get this: 1 2 3 + *
I think I am going wrong somewhere in my while loop but I don't really know. I tried to follow the example on the Wikipedia article.
I forgot I had to pop from the operator stack back into the output stack at the end.
Comparing your code
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
with the Wikipedia code https://en.wikipedia.org/wiki/Shunting-yard_algorithm
- an operator o1:
while (
there is an operator o2 other than the left parenthesis at the top
of the operator stack, and (o2 has greater precedence than o1
or they have the same precedence and o1 is left-associative)
):
pop o2 from the operator stack into the output queue
push o1 onto the operator stack
It looks like they are functionally identical.
So I suspect the problem is not with the code, but instead with the precedence table. If you have the precedence of + and * the wrong way round, then you would get this behaviour. It is easy to get this mixed up as some source have precedence going from tighter binding to loser one and some have the opposite. Compare Wikipedia order of operations and Operator Precedence in Java, use the former.
I want to open orders by orders whenever a certain trading condition is met.
I want to open pending orders in previous highest and lowest price.
So, I tried like this:
upper=iHigh(Symbol(),Period(),iHighest(Symbol(),Period(),MODE_HIGH,periods,0));
lower=iLow(Symbol(),Period(),iLowest(Symbol(),Period(),MODE_LOW,periods,0));
Comment("Upper: ",upper,"\nLower: ",lower);
int openCount=0;
int openpendCount=0;
for( int i = OrdersTotal()-1; i >= 0 ; i--)
{
if (OrderSelect(i, SELECT_BY_POS) && // Only my orders :
OrderMagicNumber() == 0 && // my magic number
OrderSymbol() == _Symbol) // and my symbol
{
if(OrderType() == OP_SELL && OrderType() ==OP_BUY) // count market orders
openCount++;
if(OrderType() == OP_SELLLIMIT && OrderType() ==OP_BUYLIMIT) // count market orders
openpendCount++;
}
}
if(openCount ==0 && openpendCount == 0 )
{ OrderSend(Symbol(), OP_SELLLIMIT,1,Ask+(upper-Ask), 3,0,0,"Sub Buy", MAGIC,0, Blue);
OrderSend(Symbol(), OP_BUYLIMIT,1,Ask-(Bid-lower), 3,0,0,"Sub Buy", MAGIC,0, Blue);
}
But no success,
Q: How can I make multiple new orders at the same time, and no more new orders when trade condition meet.
There are a number of problems with your code and it is difficult to know all the problems as you have not included your full code. However, try the following, it addresses the main issues I can see which are.
You should only check once on the close of each new bar
You need to check for successful selection of orders before working with them
Do not check for a magic number of 0, this indicates manually placed orders
You are mixing up && and || when checking your order types
You are placing your orders at strange levels. You need to set them at the previously found levels (adjusted for spread for buy orders).
int MAGIC=123;
datetime TimeBar;
int periods=50;
int start()
{
if(TimeBar==Time[0]) return(0);
double upper=iHigh(NULL, 0, iHighest(NULL, 0, MODE_HIGH, periods, 0));
double lower=iLow (NULL, 0, iLowest (NULL, 0, MODE_LOW , periods, 0));
Comment("Upper: ",upper,"\r\nLower: ",lower);
int openOrders=0;
int limitOrders=0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS))
{
if(OrderMagicNumber()!=MAGIC || OrderSymbol()!=Symbol()) continue;
if(OrderType()==OP_SELL || OrderType()==OP_BUY) openOrders++;
if(OrderType()==OP_SELLLIMIT || OrderType()==OP_BUYLIMIT) limitOrders++;
}
}
if(openOrders==0 && limitOrders==0)
{
int res;
res=OrderSend(Symbol(), OP_SELLLIMIT, 1, upper, 3, 0, 0, "Sub Sell", MAGIC, 0, clrBlue);
res=OrderSend(Symbol(), OP_BUYLIMIT, 1, lower+(Ask-Bid), 3, 0, 0, "Sub Buy", MAGIC, 0, clrBlue);
}
TimeBar=Time[0];
return(0);
}
You will also need to address the problem that the EA could potentially try to open an order within MarketInfo(Symbol(), MODE_STOPLEVEL) of the current price which would cause the order to be rejected by the trade server.
It is also good practice to check your OrderSend for errors.
I tried the code below but again it wasn't exactly as I wanted.
Only 1 pearl flood is coming. There are 90 floods.
RT ones should not come and should only come flood by call.
as an example I shared the picture. What do I have to do in this situation.
const int MaxSearchEntriesToReturn = 100;
const int SearchRateLimit = 180;
string searchTerm = "HANEDANLAR MASASININ YER ALTI EGEMENLİĞİ:RİO TİNTO";
// oldest id you already have for this search term
ulong sinceID = 1;
// used after the first query to track current session
ulong maxID;
var combinedSearchResults = new List<Status>();
List<Status> searchResponse =
await
(from search in ctx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
if (searchResponse != null)
{
combinedSearchResults.AddRange(searchResponse);
ulong previousMaxID = ulong.MaxValue;
do
{
// one less than the newest id you've just queried
maxID = searchResponse.Min(status => status.StatusID) - 1;
Debug.Assert(maxID < previousMaxID);
previousMaxID = maxID;
searchResponse =
await
(from search in ctx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.MaxID == maxID &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
combinedSearchResults.AddRange(searchResponse);
} while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit);
combinedSearchResults.ForEach(tweet =>
Console.WriteLine(
"\n User: {0} ({1})\n Tweet: {2}",
tweet.User.ScreenNameResponse,
tweet.User.UserIDResponse,
tweet.Text ?? tweet.FullText)
);
}
else
{
Console.WriteLine("No entries found.");
}
ViewBag.Twet = combinedSearchResults.ToList();
I own LINQ to Twitter. A paged search can return more values. Here's an example:
const int MaxSearchEntriesToReturn = 100;
const int SearchRateLimit = 180;
string searchTerm = "Flood Name";
// oldest id you already have for this search term
ulong sinceID = 1;
// used after the first query to track current session
ulong maxID;
var combinedSearchResults = new List<Status>();
List<Status> searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
if (searchResponse != null)
{
combinedSearchResults.AddRange(searchResponse);
ulong previousMaxID = ulong.MaxValue;
do
{
// one less than the newest id you've just queried
maxID = searchResponse.Min(status => status.StatusID) - 1;
Debug.Assert(maxID < previousMaxID);
previousMaxID = maxID;
searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.MaxID == maxID &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
combinedSearchResults.AddRange(searchResponse);
} while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit);
combinedSearchResults.ForEach(tweet =>
Console.WriteLine(
"\n User: {0} ({1})\n Tweet: {2}",
tweet.User.ScreenNameResponse,
tweet.User.UserIDResponse,
tweet.Text ?? tweet.FullText));
}
else
{
Console.WriteLine("No entries found.");
}
There are a few things to pay attention to:
Set Count to MaxSearchEntriesToReturn because it defaults to 15 and you want to minimize the number of queries.
The while loop checks SearchRateLimit because there are rate limits that will cause you to get an HTTP 429. The rate limit for App-Only is higher than the 180 I've added here.
Notice how I'm using SinceID and MaxID to page through results. See Working with Timelines in the Twitter API docs to understand what those are.
Also, please read the Search API docs and notice that the standard search API is focused on relevance and not completeness.
You all might have came across the scenarios like the following ones:
-(int) fightMath(int one, int two) {
if(one == 0 && two == 0) { result = 0; }
else if(one == 0 && two == 1) { result = 0; }
else if(one == 0 && two == 2) { result = 1; }
else if(one == 0 && two == 3) { result = 2; }
else if(one == 1 && two == 0) { result = 0; }
else if(one == 1 && two == 1) { result = 0; }
else if(one == 1 && two == 2) { result = 2; }
else if(one == 1 && two == 3) { result = 1; }
else if(one == 2 && two == 0) { result = 2; }
else if(one == 2 && two == 1) { result = 1; }
else if(one == 2 && two == 2) { result = 3; }
else if(one == 2 && two == 3) { result = 3; }
else if(one == 3 && two == 0) { result = 1; }
else if(one == 3 && two == 1) { result = 2; }
else if(one == 3 && two == 2) { result = 3; }
else if(one == 3 && two == 3) { result = 3; }
return result;
}
In short, how to effectively simplify the above scenario in Objective-C's ambience?
Any Suggestions/Ideas/Solutions ?
Cheers :)
Edit: For reference , scenario taken from here.I hope this question might save even one sec of needy developer.
Objective C is built over C. So any good C solution will be also appropriate for Objective C. Like
int result[][4] = {
{ 0, 0, 1, 2 },
{ 0, 0, 2, 1 },
{ 2, 1, 3, 3 },
{ 1, 2, 3, 3 }
};
return result[one][two]
As I know there is no Objective C - specific good practices for such problems.