Mql4 boolean logical problems - mql4

Hello I want some help with this little piece of code. Could you tell me what is wrong with it? Thank you.
if(Cross(15, iMA(NULL, PERIOD_H1, 3, 0, MODE_SMA, PRICE_CLOSE, 0) < iMA(NULL, PERIOD_H1, 80, 0, MODE_SMA, PRICE_CLOSE, 0))
&& if(Cross (16, iMA(NULL, PERIOD_M1, 3, 0, MODE_SMA, PRICE_CLOSE, 0) > iMA(NULL, PERIOD_M1, 20, 0, MODE_SMA, PRICE_CLOSE, 0)) //Moving Average crosses above Moving Average
//Moving Average crosses below Moving Average
))
{
RefreshRates();
price = Ask;
if(IsTradeAllowed())
{
ticket = myOrderSend(OP_BUY, price, TradeSize, "");
if(ticket <= 0) return;
}
else //not autotrading => only send alert
myAlert("order", "");
}

if(Cross(15,iMA(NULL,PERIOD_H1,3,0,MODE_SMA,PRICE_CLOSE,0) <
iMA(NULL,PERIOD_H1,80,0,MODE_SMA,PRICE_CLOSE,0)) &&
Cross(16,iMA(NULL,PERIOD_M1,3,0,MODE_SMA,PRICE_CLOSE,0) >
iMA(NULL,PERIOD_M1,20,0,MODE_SMA,PRICE_CLOSE,0)))
//Moving Average crosses above Moving Average
{
RefreshRates();
price = Ask;
if(IsTradeAllowed())
{
ticket = myOrderSend(OP_BUY, price, TradeSize, "");
if(ticket <= 0) return;
}
else //not autotrading => only send alert
myAlert("order", "");
}
}

Related

Request for Counter Testcase with Google Foobar Question - Prepare the Bunnies Escape [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I recently came across GoogleFoobar's problem Prepare the Bunnies Escape, and I submitted a Shortest Path based solution.
However, only 3 / 5 cases passed, and I am really intrigued to know why.
I have attached my code below for reference.
If anyone can "Hack" my solution / provide a countercase / tell me what I am doing wrong, that would be appreciated.
PLEASE DO NOT SEND ME IMPLEMENTATIONS, verbal explanations of my mistakes / counter tests would be appreciated.
Thanks.
import java.util.PriorityQueue;
public class Solution
{
public static int ans = Integer.MAX_VALUE;
public static int dx [] = {0,0,-1,1};
public static int dy [] = {-1,1,0,0};
static class State implements Comparable<State>
{
int x,y,moves;
boolean wentThroughWall;
public State(int x, int y, int moves, boolean wentThroughWall)
{
this.x = x;
this.y = y;
this.moves = moves;
this.wentThroughWall = wentThroughWall;
}
public int compareTo(State other)
{
return moves - other.moves;
}
}
public static int solution(int[][] map)
{
PriorityQueue<State> enque = new PriorityQueue<State>();
boolean visited [][] = new boolean [map.length][map[0].length];
enque.add(new State(0, 0, 1,false));
while(!enque.isEmpty())
{
State top = enque.poll();
if(top.x == map.length - 1 && top.y == map[0].length - 1)
{
ans = Math.min(ans, top.moves);
continue;
}
if(visited[top.x][top.y])
continue;
visited[top.x][top.y] = true;
for(int i = 0; i < dx.length; i++)
{
int nx = top.x + dx[i];
int ny = top.y + dy[i];
if(nx < 0 || nx >= map.length || ny < 0 || ny >= map[0].length || (map[nx][ny] == 1 && top.wentThroughWall))
continue;
if(map[nx][ny] == 1)
enque.add(new State(nx, ny, top.moves + 1, true));
else
enque.add(new State(nx, ny, top.moves + 1, top.wentThroughWall));
}
}
return ans;
}
public static void main(String[] args) {
int [][] test = {{0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0}};
System.out.println(Solution.solution(test));
}
}
Statement:
You're awfully close to destroying the LAMBCHOP doomsday device and freeing Commander Lambda's bunny prisoners, but once they're free of the prison blocks, the bunnies are going to need to escape Lambda's space station via the escape pods as quickly as possible. Unfortunately, the halls of the space station are a maze of corridors and dead ends that will be a deathtrap for the escaping bunnies. Fortunately, Commander Lambda has put you in charge of a remodeling project that will give you the opportunity to make things a little easier for the bunnies. Unfortunately (again), you can't just remove all obstacles between the bunnies and the escape pods - at most you can remove one wall per escape pod path, both to maintain structural integrity of the station and to avoid arousing Commander Lambda's suspicions.
You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1).
Write a function solution(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed.
Languages
To provide a Python solution, edit solution.py
To provide a Java solution, edit Solution.java
Test cases
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Python cases --
Input:
solution.solution([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]])
Output:
7
Input:
solution.solution([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]])
Output:
11
-- Java cases --
Input:
Solution.solution({{0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0}})
Output:
7
Input:
Solution.solution({{0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0}})
Output:
11
Sike, I fixed it. I managed to generate a bunch of testcases using a random test case generator, and realized that my visited array isn't defined correctly.
I have listed the correct solution below for reference with the fix.
import java.util.PriorityQueue;
public class Solution
{
public static int ans = Integer.MAX_VALUE;
public static int dx [] = {0,0,-1,1};
public static int dy [] = {-1,1,0,0};
static class State implements Comparable<State>
{
int x,y,moves;
boolean wentThroughWall;
public State(int x, int y, int moves, boolean wentThroughWall)
{
this.x = x;
this.y = y;
this.moves = moves;
this.wentThroughWall = wentThroughWall;
}
public int compareTo(State other)
{
return moves - other.moves;
}
}
public static int solution(int[][] map)
{
PriorityQueue<State> enque = new PriorityQueue<State>();
boolean visited [][][] = new boolean [map.length][map[0].length][2];
enque.add(new State(0, 0, 1,false));
while(!enque.isEmpty())
{
State top = enque.poll();
if(top.x == map.length - 1 && top.y == map[0].length - 1)
{
ans = Math.min(ans, top.moves);
continue;
}
if(visited[top.x][top.y][(top.wentThroughWall ? 0 : 1)])
continue;
visited[top.x][top.y][(top.wentThroughWall ? 0 : 1)] = true;
for(int i = 0; i < dx.length; i++)
{
int nx = top.x + dx[i];
int ny = top.y + dy[i];
if(nx < 0 || nx >= map.length || ny < 0 || ny >= map[0].length || (map[nx][ny] == 1 && top.wentThroughWall))
continue;
if(map[nx][ny] == 1)
enque.add(new State(nx, ny, top.moves + 1, true));
else
enque.add(new State(nx, ny, top.moves + 1, top.wentThroughWall));
}
}
assert(ans != Integer.MAX_VALUE);
return ans;
}
public static void main(String[] args) {
int [][] test = {{0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0}};
System.out.println(Solution.solution(test));
}
}
As a competitive person myself, I would like to know if my code really works, or was it just weak testing.
If you find a testcase which breaks my code, please let me know in the comments and I will get back to you ASAP.

Expert Advisor is not opening trades

I tried to create an EA in mql4 which opens and close the trade position as per condition given, but it is not opening the trade after mating the conditions, EA Works till signal which shows buy and sell and after that nothing happens. How can I debug this?
void CloseBuyPosition()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
string Cp = OrderSymbol();
if (_Symbol == Cp)
if (OrderType() == OP_BUY)
{
OrderClose(OrderTicket(), OrderLots(), Bid, 3, NULL);
}
}
}
void CloseSellPosition()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
string Cp = OrderSymbol();
if (_Symbol == Cp)
if (OrderType() == OP_SELL)
{
OrderClose(OrderTicket(), OrderLots(), Ask, 3, NULL);
}
}
}
void OnTick()
{
string signal = "";
double Sar = iSAR(_Symbol, _Period, 0.02, 0.2, 0);
if (Sar < Low[1] && Open[1] < Close[1])
{
signal = "buy";
}
if (Sar > High[1] && Open[1] > Close[1])
{
signal = "sell";
}
if (signal == "buy" && OrdersTotal() == 0)
OrderSend(_Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green);
if (signal == "sell" && OrdersTotal() == 0)
OrderSend(_Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red);
Comment("The Signal is :", signal);
if (Open[1] > Close[1] && OrdersTotal() > 0)
CloseBuyPosition();
if (Open[1] < Close[1] && OrdersTotal() > 0)
CloseSellPosition();
}
Step 0:check, whether your EA was launched inside MetaTrader4 Terminal with an active permission to actually do trades.
Step 1:check the code, for having at least some elementary self-debugging tools ( GetLastError() and Print() are way better than intermittent and self-destroying, i.e. having Zero-depth of history GUI-text inside but a last visible Comment()
Step 2:Analyze the logs, where all printed details will help you trace the root cause ( Broker-rejections, closed Market, flawed price-levels and many of the possible reasons for an OrderSend()-call to get rejected )
int OrderSend( string symbol, // symbol
int cmd, // operation
double volume, // volume
double price, // price
int slippage, // slippage
double stoploss, // stop loss <------------ PRICE-DOMAIN levels, not INT-s
double takeprofit, // take profit <---------- PRICE-DOMAIN levels, not INT-s
string comment = NULL, // comment
int magic = 0, // magic number
datetime expiration = 0, // pending order expiration
color arrow_color = clrNONE// color
);
void OnTick()
{
/* string signal = "";
double Sar = iSAR( _Symbol, _Period, 0.02, 0.2, 0 );
if ( Sar < Low[1] && Open[1] < Close[1] ) signal = "buy";
if ( Sar > High[1] && Open[1] > Close[1] ) signal = "sell";
if ( signal == "buy" && OrdersTotal() == 0 ) OrderSend( _Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green );
if ( signal == "sell" && OrdersTotal() == 0 ) OrderSend( _Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red );
Comment( "The Signal is :", signal );
if ( Open[1] > Close[1] && OrdersTotal() > 0 ) CloseBuyPosition();
if ( Open[1] < Close[1] && OrdersTotal() > 0 ) CloseSellPosition();
*/
static int count_of_NOPs = 0;
if ( OrdersTotal() == 0 )
{ if ( Open[1] < Close[1]
&& Low[1] > iSAR( _Symbol, _Period, 0.02, 0.2, 0 )
) {
int rc = OrderSend( _Symbol, OP_BUY, 0.01, Ask, 3, 20, 100, NULL, 0, 0, Green );
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID TRY OrderSend( OP_BUY ) -> RESULTING RetCode ( tkt# ) == %d [yield GetLastError() == %d]",
rc,
GetLastError()
)
);
count_of_NOPs = 0; //------------------------------ .RESET
return; //------------------------------------------^ J.I.T./RET
}
if ( Open[1] > Close[1]
&& High[1] < iSAR( _Symbol, _Period, 0.02, 0.2, 0 )
) {
int rc = OrderSend( _Symbol, OP_SELL, 0.01, Bid, 3, 20, 100, NULL, 0, 0, Red );
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID TRY OrderSend( OP_SELL ) -> RESULTING RetCode ( tkt# ) == %d [yield GetLastError() == %d]",
rc,
GetLastError()
)
);
if ( )
count_of_NOPs = 0; //------------------------------ .RESET
return; //------------------------------------------^ J.I.T./RET
}
/* OTHERWISE: */
Print( StringFormat( "HAVING NO ORDERS ACTIVE... DID NOP... (for %d time)",
++count_of_NOPs
)
);
// */
}
else
{ if ( Open[1] > Close[1] ) { Print( StringFormat( "HAVING %d ORDERS ACTIVE... WILL TRY CloseBuyPosition()...",
OrdersTotal()
)
);
CloseBuyPosition();
count_of_NOPs = 0; //---------- .RESET
return; //----------------------^ J.I.T./RET
}
if ( Open[1] < Close[1] ) { Print( StringFormat( "HAVING %d ORDERS ACTIVE... WILL TRY CloseSellPosition()...",
OrdersTotal()
)
);
CloseSellPosition();
count_of_NOPs = 0; //---------- .RESET
return; //----------------------^ J.I.T./RET
}
/* OTHERWISE: */
Print( StringFormat( "HAVING %d ORDERS ACTIVE... DID NOP... (for %d time)",
OrdersTotal(),
++count_of_NOPs
)
);
// */
}

How do I to use Bollinger Bands to get a signal to open an order?

I'm trying to use the Bollinger Bands to get a signal to open orders buy or sell. To do this, I am trying to test if candle[2] and candle[1] are closing above or below MODE_UPPER and MODE_LOWER of iBands to open the order. The problem is that the order are opening next to MODE_MAIN instead of MODE_UPPER or MODE_LOWER and I don't know why it happening.
How could I do this ?
Trying
//return true if has a signal to open order
bool bollingerBandScalper(int bs){
int _candle = 0;
int _period = 14;
//double _main = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_MAIN, _candle + 1);
double LowerBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_LOWER, _candle + 1);
double UpperBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_UPPER, _candle + 1);
double PrevLowerBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_LOWER, _candle + 2);
double PrevUpperBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_UPPER, _candle + 2);
//buy signal
if(bs == OP_BUY){
if((Close[_candle + 2] > PrevLowerBB) && (Close[_candle + 1] > LowerBB)){
return true;
}
}
//sell signal
if(bs == OP_SELL){
if((Close[_candle + 2] > PrevUpperBB) && (Close[_candle + 1] > UpperBB)){
return true;
}
}
return false;
}
I think you've made a mistake to find where price closes above/below BB Bands.
I made some changes in your code. You can test it:
//return true if has a signal to open order
bool bollingerBandScalper(int type,int period,int shift)
{
double LowerBB = iBands(_Symbol,_Period,period,2.0,0,PRICE_CLOSE,MODE_LOWER,shift+1);
double UpperBB = iBands(_Symbol,_Period,period,2.0,0,PRICE_CLOSE,MODE_UPPER,shift+1);
double PrevLowerBB = iBands(_Symbol,_Period,period,2,0,PRICE_CLOSE,MODE_LOWER,shift+2);
double PrevUpperBB = iBands(_Symbol,_Period,period,2,0,PRICE_CLOSE,MODE_UPPER,shift+2);
//buy signal
if(type==OP_BUY && Close[shift+2]>PrevLowerBB && Close[shift+1]<LowerBB) return true;
//sell signal
if(type==OP_SELL && Close[shift+2]<PrevUpperBB && Close[shift+1]>UpperBB) return true;
return false;
}

MQL4 Expert Advisor isn't doing anything

This bot is supposed to buy based on support and resistance, stop loss is based on support resistance of the moving averages. When I test it out it won't do anything trying. How do I debug this to do what I want it to do?
After viewing the code do you have any suggestions input or criticism?
I tried to comment the code the best I could to make sense.
#property strict
string BotName = "SRMATrader";
/********** SETTINGS *************/
extern int Magic = 8008;
string CandleColor;
int MaxCloseSpreadPips = 600;
int MaxTrades = 1; // was 10
int AcceptableSpread = 2;
double LotsToTrade = .2; // 0.1
double StopLoss = -3700; // 3800
double ProfitTarget = 20.00; // $280 at 2.0 trade size
int MaxOpenOrderDurationSeconds = (5 * 24 * 60 * 60); // 5 days was profitable
int TradeDelayTimeSeconds = 30; //(10 * 24 * 60 * 60); // 10 Days
int PendingOrderExpirationSeconds = (4 * 24 * 60 * 60); // 4 Days
datetime LastTradePlacedTimestamp = 0;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
// MAIN LOOP
void OnTick()
{
double CurrentPrice = MarketInfo(Symbol(), MODE_BID);
double CandleResistance = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_HIGH, 0);
double CandleSupport = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_LOW, 0);
// Should we place a trade?
if (GetTotalOpenTrades() < MaxTrades)
{
if ( (TimeCurrent() - LastTradePlacedTimestamp) > TradeDelayTimeSeconds )
{
// long
if ( CurrentPrice <= CandleSupport )
{
if (CandleColor == "Green")
{
PlacePendingOrder("Green", LotsToTrade, CandleSupport, PendingOrderExpirationSeconds);
LastTradePlacedTimestamp = TimeCurrent();
}
}
// short
if ( CurrentPrice >= CandleResistance)
{
if (CheckForTradeSetup() == "Red" )
{
PlacePendingOrder("Red", LotsToTrade, CandleResistance, PendingOrderExpirationSeconds);
LastTradePlacedTimestamp = TimeCurrent();
}
}
}
}
if (GetTotalOpenTrades() > 0)
{
CloseTradeAfterAge(MaxOpenOrderDurationSeconds);
CheckForOrderClose(ProfitTarget, StopLoss);
}
} // end OnTick()
string CheckForTradeSetup()
{
double CurrentPrice = MarketInfo(Symbol(), MODE_BID);
double CandleSupport = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_LOW, 0);
double CandleResistance = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_HIGH, 0);
if ( CurrentPrice <= CandleSupport )
{
CandleColor = "Green";
}
if ( CurrentPrice >= CandleResistance )
{
CandleColor = "Red";
}
return "no-setup";
}
void PlacePendingOrder(string Trade_Type, double Lots, double At_Price, int Expiration_Seconds)
{
int TicketResult = 0;
datetime Expiration_Time = (TimeCurrent() + Expiration_Seconds);
double Price = NormalizeDouble(At_Price, Digits);
if (Trade_Type == "Green")
{
if (Ask < At_Price) return;
double StopPrice = CalculateStopLossPrice(Price, Lots, StopLoss, Trade_Type);
TicketResult = OrderSend(Symbol(), OP_BUYLIMIT, Lots, Price, 10, StopPrice, 0, " Buy", Magic, Expiration_Time, clrGreen);
}
if (Trade_Type == "Red")
{
if (Bid > At_Price) return;
double StopPrice = CalculateStopLossPrice(Price, Lots, StopLoss, Trade_Type);
TicketResult = OrderSend(Symbol(),OP_SELLLIMIT, Lots, NormalizeDouble(At_Price, Digits), 10, StopPrice, 0, " Sell", Magic, Expiration_Time, clrRed);
}
if(TicketResult < 0)
{
Print("OrderSend failed with error #",GetLastError());
}
else
{
Print("OrderSend placed successfully");
}
}
double CalculateStopLossPrice(double OrderPrice, double TradeSize, double StopLossDollars, string PositionType)
{
// Convert stop loss dollars to positive number
double CurrentSpread = MarketInfo(Symbol(), MODE_SPREAD);
Print("*** CurrentSpread: ", CurrentSpread);
double PipValue = (TradeSize * 10);
double StopLossPips = (StopLossDollars / PipValue);
double CandleSupport = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_LOW, 0);
double CandleResistance = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_HIGH, 0);
if (PositionType == "Green")
{
double StopLossPrice = CandleResistance;
}
if (PositionType == "Red")
{
double StopLossPrice = CandleSupport;
}
return 0.0;
}
void CloseAllTrades()
{
int CloseResult = 0;
for(int t=0; t<OrdersTotal(); t++)
{
if(OrderSelect(t, SELECT_BY_POS,MODE_TRADES))
{
if(OrderMagicNumber() != Magic) continue;
if(OrderSymbol() != Symbol()) continue;
if(OrderType() == OP_BUY) CloseResult = OrderClose(OrderTicket(), OrderLots(), Bid, MaxCloseSpreadPips, clrRed);
if(OrderType() == OP_SELL) CloseResult = OrderClose(OrderTicket(), OrderLots(), Ask, MaxCloseSpreadPips, clrGreen);
t--;
}
}
if(CloseResult < 0)
{
Print("OrderSend failed with error #", GetLastError());
}
else
{
Print("OrderSend placed successfully");
}
return;
}
int GetTotalOpenTrades()
{
int TotalTrades = 0;
for (int t=0; t<OrdersTotal(); t++)
{
if(OrderSelect(t, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() != Symbol()) continue;
if(OrderMagicNumber() != Magic) continue;
if(OrderCloseTime() != 0) continue;
TotalTrades = (TotalTrades + 1);
}
}
return TotalTrades;
}
double GetTotalProfits()
{
double TotalProfits = 0.0;
for (int t=0; t<OrdersTotal(); t++)
{
if(OrderSelect(t, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() != Symbol()) continue;
if(OrderMagicNumber() != Magic) continue;
if(OrderCloseTime() != 0) continue;
TotalProfits = (TotalProfits + OrderProfit());
}
}
return TotalProfits;
}
// Close all trades if we are at profit or loss
void CheckForOrderClose(double Target, double Stop)
{
// check for profit or loss
if (GetTotalProfits() > Target)
{
CloseAllTrades();
}
}
// Close if trade is more than (n) seconds old
string CloseTradeAfterAge(int MaxOpenTradeAgeSeconds)
{
for(int t=0; t < OrdersTotal(); t++)
{
if(OrderSelect(t, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() != Symbol()) return "wrong symbol";
if(OrderMagicNumber() != Magic) return "magic number does not match";
if(OrderCloseTime() != 0) return "order already closed";
datetime OrderOpenTime = OrderOpenTime();
string Now = (TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS));
datetime NowTimeStamp = (StrToTime(Now));
if ((NowTimeStamp - OrderOpenTime) > MaxOpenTradeAgeSeconds) // 1 * 24 * 60 * 60
{
if ((OrderType() == 0) || (OrderType() == 1)) // Only close orders that are live (not limit ordes)
{
CloseAllTrades();
return "all trades closed";
}
}
}
}
return "trades not closed";
}
check and go over this piece of code until you are sure you understand the logic and make it working
//...
if (CandleColor == "Green") //this one is NULL
{
PlacePendingOrder("Green", LotsToTrade, CandleSupport, PendingOrderExpirationSeconds);
LastTradePlacedTimestamp = TimeCurrent();
}
}
// short
if ( CurrentPrice >= CandleResistance)
{
if (CheckForTradeSetup() == "Red" )//this fn() returns "no-setup"
//....
so edit the CheckForTradeSetup() function and call it before checking the colors, and also comparing two strings is a very bad idea because it is too slow. +1/0/-1 or enums or even colors (==int) is preferred

OpenCv & EmguCv equavalent method?

As berak said in the comments, it seems this code is deprecated
In Opencv there is a method "cvmget", the sample usage is:
bool niceHomography(const CvMat * H)
{
const double det = cvmGet(H, 0, 0) * cvmGet(H, 1, 1) - cvmGet(H, 1, 0) * cvmGet(H, 0, 1);
if (det < 0)
return false;
const double N1 = sqrt(cvmGet(H, 0, 0) * cvmGet(H, 0, 0) + cvmGet(H, 1, 0) * cvmGet(H, 1, 0));
if (N1 > 4 || N1 < 0.1)
return false;
const double N2 = sqrt(cvmGet(H, 0, 1) * cvmGet(H, 0, 1) + cvmGet(H, 1, 1) * cvmGet(H, 1, 1));
if (N2 > 4 || N2 < 0.1)
return false;
const double N3 = sqrt(cvmGet(H, 2, 0) * cvmGet(H, 2, 0) + cvmGet(H, 2, 1) * cvmGet(H, 2, 1));
if (N3 > 0.002)
return false;
return true;
}
is there any method in like cvmget in EmguCV?
cvmget function returns the element of the single channel array. This function is a fast replacement for GetReal2D
In EmguCV you can use the cvGetReal2D method of the CvInvoke class
So, the code in the link you provided should be like:
bool niceHomography(Image<Gray, byte> H)
{
double det = CvInvoke.cvGetReal2D(H, 0, 0) * CvInvoke.cvGetReal2D(H, 1, 1) - CvInvoke.cvGetReal2D(H, 1, 0) * CvInvoke.cvGetReal2D(H, 0, 1);
if (det < 0)
return false;
double N1 = Math.Sqrt(CvInvoke.cvGetReal2D(H, 0, 0) * CvInvoke.cvGetReal2D(H, 0, 0) + CvInvoke.cvGetReal2D(H, 1, 0) * CvInvoke.cvGetReal2D(H, 1, 0));
if (N1 > 4 || N1 < 0.1)
return false;
double N2 = Math.Sqrt(CvInvoke.cvGetReal2D(H, 0, 1) * CvInvoke.cvGetReal2D(H, 0, 1) + CvInvoke.cvGetReal2D(H, 1, 1) * CvInvoke.cvGetReal2D(H, 1, 1));
if (N2 > 4 || N2 < 0.1)
return false;
double N3 = Math.Sqrt(CvInvoke.cvGetReal2D(H, 2, 0) * CvInvoke.cvGetReal2D(H, 2, 0) + CvInvoke.cvGetReal2D(H, 2, 1) * CvInvoke.cvGetReal2D(H, 2, 1));
if (N3 > 0.002)
return false;
return true;
}
PS. Be sure that your array(Image) has just one channel(Grayscale) otherwise a runtime error will be raised. If your array has multiple channels use the cvGet2D method instead.
OpenCV Documentation: mGet

Resources