How do I correct an error code 0 in MQL4 OrderModify() call? - algorithmic-trading

I have this code below which I am using to test trailing stop function. It works on some currency pairs and doesn't work in others. It's returning error code 0 (zero). I will be grateful if somebody can help me out
void modifyTrade() {
TrailingStop = MarketInfo(Symbol(), MODE_STOPLEVEL);
if(TrailingStop>0)
{
for(int z = 0; z<OrdersTotal(); z++)
{
OrderSelect(z,SELECT_BY_POS);
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
bool res=OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-Point*TrailingStop,Digits),OrderTakeProfit(),0,Blue);
if(!res) {
Print("Error in OrderModify. Error code=",GetLastError());
//if(Symbol()=="EURNZD")
Alert("Error in OrderModify. Error code=",GetLastError()," ; ",OrderSymbol());
}
else {
Print("Order modified successfully.");
}
}
}
}
}
}

Error being
0 == ERR_NO_ERROR ... No error returned
is rather ok, no need to "correct" it, it means there was nothing to actually improve.
There are a few risky points to mention - prices move, STOPLEVEL parameter can either ( be careful on this - a hostile case if appears in live-trading ) and also be informed, that there are other levels, that may prohibit an OrderModify()-call from being Broker-T&C-compliant (and will get rejected for that reason)
Somehow improved code may work in this sense :
void modifyTrade()
{
TrailingStop = MarketInfo( Symbol(), MODE_STOPLEVEL );
if ( TrailingStop > 0 )
{
for ( int z = 0; z < OrdersTotal(); z++ )
{
if !OrderSelect( z, SELECT_BY_POS ) continue;
// ______________________________________________________ CRITICAL
RefreshRates();
// ______________________________________________________ Bid + Ask valid...
if ( TrailingStop != MarketInfo( OrderSymbol(), MODE_STOPLEVEL ) )
{ // TrailingStop CHANGED ... LOG, renegotiate such Broker policy
TrailingStop = MarketInfo( OrderSymbol(), MODE_STOPLEVEL
}
// ______________________________________________________ STOPLEVEL valid...
if ( Bid - OrderOpenPrice() > Point * TrailingStop
&& OrderType() == OP_BUY )
{
if ( OrderStopLoss() < Bid - Point * TrailingStop )
{
bool res = OrderModify( OrderTicket(),
OrderOpenPrice(),
NormalizeDouble( Bid - Point * TrailingStop, Digits ),
OrderTakeProfit(),
0,
Blue
);
if ( !res )
{
Print( "Error in OrderModify. Error code=", _LastError );
// if ( Symbol() == "EURNZD" )
Alert( "Error in OrderModify. Error code=", _LastError, " ; ", OrderSymbol() );
}
else
{
Print( "Order modified successfully." );
}
}
}
if ( OrderOpenPrice() - Ask > Point * TrailingStop
&& OrderType() == OP_SELL )
{
...
}
}
}
}

There are a couple of errors in your code.
once called, GetLastError() is reset. If you are both printing and alerting the last error, you should store the error code prior to printing/alerting.
you should check OrderSelect() succeeds.
you should iterate over orders in the opposite direction to ensure your code carried on operating should an order be closed mid-check.
You require different code for longs and shorts
Your code is prone to errors simply because you have no buffer and are trying to trail price at the minimum stop level. By the time your order modification is received by the trading server it is highly likely price may have moved back inside the stop level area resulting in a modification error.
void modifyTrade()
{
TrailingStop = MarketInfo(Symbol(), MODE_STOPLEVEL);
if(TrailingStop>0)
{
for(int z=OrdersTotal()-1; z>=0; z--)
{
if(OrderSelect(z,SELECT_BY_POS))
{
if(OrderType()==OP_BUY)
{
if(Bid-OrderStopLoss()>TrailingStop*point)
{
bool res=OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-Point*TrailingStop,Digits),OrderTakeProfit(),0,Blue);
if(!res)
{
int err=GetLastError();
Print("Error in OrderModify. Error code=",err);
Alert("Error in OrderModify. Error code=",err);
}
else Print("Order modified successfully.");
}
}
if(OrderType()==OP_SELL)
{
if(OrderStopLoss()-Ask>TrailingStop*point)
{
bool res=OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask+Point*TrailingStop,Digits),OrderTakeProfit(),0,Blue);
if(!res)
{
int err=GetLastError();
Print("Error in OrderModify. Error code=",err);
Alert("Error in OrderModify. Error code=",err);
}
else Print("Order modified successfully.");
}
}
}
}
}
}

Related

Adding a trailing Stop loss to an expert advisor using MQL5

Hi I'm new to MQL5 and I wanted to add a trailing stop loss to my expert advisor but some reason it does not add. Here is the code:
if(PositionSelect(_Symbol) && UseTrailingStop == true)
{
double TrailingStop = (atr[1] * 3) + close[1];
Trail.TrailingStop(_Symbol,TrailingStop,0,0);
}
Please note that close[1] is for the close price of the previous bar and atr[1] is for the value of the average true range. What am i doing wrong?????
There you go: hope this is helpful.
//--- trailing position
for(i=0;i<PositionsTotal();i++)
{
if(Symbol()==PositionGetSymbol(i))
{
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
{
sl=MathMax(PositionGetDouble(POSITION_PRICE_OPEN)+Spread*_Point,Bid-SL*_Point);
if(sl>PositionGetDouble(POSITION_SL) && (Bid-StopLevel*_Point-Spread*_Point)>PositionGetDouble(POSITION_PRICE_OPEN))
{
request.action = TRADE_ACTION_SLTP;
request.symbol = _Symbol;
request.sl = NormalizeDouble(sl,_Digits);
request.tp = PositionGetDouble(POSITION_TP);
OrderSend(request,result);
if(result.retcode==10009 || result.retcode==10008) // request executed
Print("Moving Stop Loss of Buy position #",request.order);
else
{
Print(ResultRetcodeDescription(result.retcode));
return;
}
return;
}
}
if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
{
sl=MathMin(PositionGetDouble(POSITION_PRICE_OPEN)-Spread*_Point,Ask+SL*_Point);
if(sl<PositionGetDouble(POSITION_SL) && (PositionGetDouble(POSITION_PRICE_OPEN)-StopLevel*_Point-Spread*_Point)>Ask)
{
request.action = TRADE_ACTION_SLTP;
request.symbol = _Symbol;
request.sl = NormalizeDouble(sl,_Digits);
request.tp = PositionGetDouble(POSITION_TP);
OrderSend(request,result);
if(result.retcode==10009 || result.retcode==10008) // request executed
Print("Moving Stop Loss of Sell position #",request.order);
else
{
Print(ResultRetcodeDescription(result.retcode));
return;
}
return;
}
}
}
}

how to check count of likes and dislike for post for rating sysytem

i am making an system to check count of likes and dislike if like count is more then dislike count then it gives true
but i am getting an error
// if (Files::withCount('likes') >= Files::withCount('dislike')) {
// return response()->json(['true']);
// }elseif (Files::withCount('dislike') >= Files::withCount('like')) {
// return response()->json(['false']);
// }else{
// return response()->json(['error'=>'somethingwenrwrng']);
// }
// if( DB::table('files')->select('files_id')
// ->join('likes','files_id.files_id','=','files_id') > DB::table('files')->select('id')
// ->join('dislike','files_id.files_id','=','files_id') ){
// return response()->json(['true']);
// }else {
// return response()->json(['error'=>'somethingwenrwrng']);
// }
$file = Files::find($id);
if($file ->likes->count() > $file ->dislike->count() ){
return response()->json(['true']);
}else{
return response()->json(['error'=>'somethingwenrwrng']);
}
i have tried different method to check but getting an error
the withCount() method return a property of the related field_count counting related models
so
$file = Files::find($id)->withCount(['likes','dislikes']);
if($file->likes_count > $file->dislikes_count ){
return response()->json(['true']);
}

IInternetProtocolRoot::Start is never called

I am working on Asynchronous Pluggable Protocol Handler according to
https://msdn.microsoft.com/en-us/library/aa767916(v=vs.85).aspx#Creating_an_Asynchro
but step 3 is not happens. Urlmon.dll is supposed to call QueryInterface on my pluggable protocol handler for its IInternetProtocol interface and it does not. I am missing something and I can not figure it out. Does anybody know what the problem?
On step 2, ParseUrl is called twice:
if( ParseAction == PARSEACTION::PARSE_SECURITY_URL ) {
if( cchResult < _countof(L"http://localhost/") ) {
return S_FALSE;
}
memcpy(pwzResult, L"http://localhost/", sizeof(L"http://localhost/"));
*pcchResult = _countof(L"http://localhost/") - 1;
return S_OK;
}
if( ParseAction == PARSEACTION::PARSE_DOMAIN ) {
if( cchResult < _countof(L"localhost") ) {
return S_FALSE;
}
memcpy(pwzResult, L"localhost", sizeof(L"localhost"));
*pcchResult = _countof(L"localhost") - 1;
return S_OK;
}
return INET_E_DEFAULT_ACTION;

Column in gwt celltable doesn't sort

I want to add sorting for column in celltable with help of ListHandler. But it doesn't sort. I don't understand why it doesn't work. My code is based on GWT tutorial.
Please suggest me something.
Contract.java
public class Contract implements Serializable {
private int contId;
private String contOrgName;
//getters and setters...
}
Main.java
TextColumn<Contract> orgNameColumn = new TextColumn<Contract>() {
#Override
public String getValue(Contract contract) {
return contract.getcontOrgName();
}};
orgNameColumn.setSortable(true);
CellTable<Contract> tableContract = new CellTable<Contract>();
tableContract.addColumn(orgNameColumn, "OrgName");
ListDataProvider<Contract> contractDataProvider = new ListDataProvider<Contract>();
contractDataProvider.addDataDisplay(tableContract);
GetContractsServiceAsync getContractsService = GWT.create(GetContractsService.class);
getContractsService.getContracts(new AsyncCallback<List<Contract>>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(List<Contract> result) {
contractDataProvider.getList().clear();
contractDataProvider.getList().addAll(result);
ListHandler<Contract> columnSortHandler = new ListHandler<Contract>(result);
columnSortHandler.setComparator(orgNameColumn, new Comparator<Contract>() {
public int compare(Contract o1, Contract o2) {
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.getcontOrgName().compareTo(o2.getcontOrgName()) : 1;
}
return -1;
}
});
tableContract.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(orgNameColumn);
}
});
Hey I was also facing the same issue a long back..Then I got to know that the object reference id is different than the one I have added into table. Once i got the reason it was very easy to find the solution.
Also please register your ListHandler before adding column to CellTable.
Note the edit for your comment :
There is nothing wrong with the comparator. The problem is still same. It reflects the wrong the object in comparator compared to in CellTable.
Please try replace the code as below :
contractDataProvider.getList().addAll(result);
ListHandler<Contract> columnSortHandler = new ListHandler<Contract>(contractDataProvider.getList());
Try to move the creation of your columnSortHandler out of the onSuccess Method. Place it right after you created your column.
At the moment you are adding the results before you add the columnSortHandler. I think that is the wrong order.
i my case, i did my sorting like this:
private void sortColumn( List<CModel> list ) {
int count = listOfColumns.size(); //upon adding the columns, i have created a list that will hold all the columns
if ( list.size() <= 0 ) {
for ( int i = 0; i < count; i++ ) {
listOfColumns.get(i).setSortable( false );
}
} else {
for ( int i = 0; i < count; i++ ) {
sort( i );
dg.redrawHeaders();
}
}
}
private void sort(int i) {
String[] listColHead = { /** list of column headers */ };
Column<CModel,?> column = listCheckoutColumns.get( i );
final String valueToCompare = listColHead[i];
final ListDataProvider<CModel> dataProvider = new ListDataProvider<CModel>();
// Connect the table to the data provider
dataProvider.addDataDisplay( dg );
// Add the data to the data provider, which automatically pushes it to the widget
List<CModel> list = dataProvider.getList();
for ( CModel product : listCheckout ) {
list.add( product );
}
column.setSortable( true );
// Add a ColumnSortEvent.ListHandler to connect sorting to the List
ListHandler<CModel> columnSortHandler = new ListHandler<CModel>( list );
columnSortHandler.setComparator( column, new Comparator<CModel>() {
public int compare( CModel p1, CModel p2 ) {
if ( p1 == p2 ) {
return 0;
}
// Compare the columns.
if ( p1 != null ) {
if ( valueToCompare.equals( "code" ) ) {
return ( p2 != null ) ? p1.getFproductid().compareTo( p2.getFproductid() ) : 1;
}
else if ( valueToCompare.equals( "desc" ) ) {
return ( p2 != null ) ? p1.getFproduct_name().compareTo( p2.getFproduct_name() ) : 1;
}
else if ( valueToCompare.equals( "type" ) ) {
return ( p2 != null ) ?
uec.computeTypeLabel( p1 ).compareTo( uec.computeTypeLabel( p2 ) ) : 1;
}
else if ( valueToCompare.equals( "maxex" ) ) {
return ( p2 != null ) ? uec.exQtyLabel( p1 ).compareTo( uec.exQtyLabel( p2 ) ) : 1;
}
else if ( valueToCompare.equals( "unit" ) ) {
return ( p2 != null ) ? p1.getFuom().compareTo( p2.getFuom() ) : 1;
}
else if ( valueToCompare.equals( "status" ) ) {
return ( p2 != null ) ? uec.qtyLabel( p1 ).compareTo( uec.qtyLabel( p2 ) ) : 1;
}
else if ( valueToCompare.equals( "qty" ) ) {
return ( p2 != null ) ? Double.compare( p1.getFqty(), p2.getFqty() ) : 1;
}
else if ( valueToCompare.equals( "price" ) ) {
return ( p2 != null ) ? uec.extPriceLabel( p1 ).compareTo( uec.extPriceLabel( p2 ) ) : 1;
}
else if ( valueToCompare.equals( "total" ) ) {
return ( p2 != null ) ? Double.compare( p1.getFtotal_line(), p2.getFtotal_line() ) : 1;
}
}
return -1;
}
});
dg.addColumnSortHandler( columnSortHandler );
dg.getColumnSortList().push( column );
}
everytime, i'll set the data for my DataGrid list,
dgCheckout.redraw();
dgCheckout.setRowCount( lengthOfList, true );
dgCheckout.setRowData( 0, newList );
sortColumn( newList );

C++ Visual Studio 2010 - Using Threads, Deque And Handlers

I'm trying to use multiple threads in an application that reads out of a large file.
I want to read from the file in the main thread and put each line into a deque called countedAddresses.
The I want multiple threads to pick lines out of countedAddresses and pull all of the email addresses out of them and place them in a deque called resolvedAddresses.
At the moment this all works if there is only one resolveAddressThread running, but if I run two I get heap corruption errors.
I launch the threads with:
_beginthread( resolveAddressThread, 0, NULL );
_beginthread( resolveAddressThread, 0, NULL );
Here is the thread code:
unsigned int linesCounted, linesResolved, linesProcessed;
std::deque<std::string> countedAddresses;std::deque<std::string> resolvedAddresses;
HANDLE linesCMutex, linesRMutex, linesRCMutex;
void resolveAddressThread(void* pParams)
{
string fileLine= "";
while(1)
{
WaitForSingleObject(linesCMutex, INFINITE);
WaitForSingleObject(linesRCMutex, INFINITE);
if (linesCounted>linesResolved)
{
if (countedAddresses.size()!=0)
{
fileLine = countedAddresses.front();
countedAddresses.pop_front();
ReleaseMutex(linesRCMutex);
ReleaseMutex(linesCMutex);
}
else
{
ReleaseMutex(linesRCMutex);
ReleaseMutex(linesCMutex);
Sleep(1000);
}
}
else
{ cout<<"All lines in the file have been processed."<<endl;
ReleaseMutex(linesRCMutex);
ReleaseMutex(linesCMutex);
break;}
if (fileLine.length()>1)
{
string::iterator strIter;
string buffer;
int tabCount=0;
bool useFlag =false, keepFlag = false, stopFlag = false;
buffer.clear();
for(strIter=fileLine.begin(); strIter!=fileLine.end(); ++strIter)
{
if (*strIter == '\t')
{
++tabCount;
}
if (tabCount == 10)
{
if ('\"'== *strIter)
{
useFlag=!useFlag;
}
else if (useFlag && *strIter > 0)
{
if (*strIter == '#')
{
buffer+=*strIter;
keepFlag = true;
}
else if ((*strIter ==' '||*strIter ==';')&& keepFlag)
{
if (buffer.at(buffer.length()-1)=='.')
{buffer = buffer.substr(0, buffer.length() - 1);}
WaitForSingleObject(linesRMutex, INFINITE);
resolvedAddresses.push_back(buffer);
ReleaseMutex(linesRMutex);
buffer.clear();
keepFlag = false;
}
else if (*strIter ==' '||*strIter ==';')
{
buffer.clear();
keepFlag = false;
}
else
{
buffer+=*strIter;
}
}
}
if (tabCount ==11 && keepFlag==true)
{
if (buffer.at(buffer.length()-1)=='.')
{buffer = buffer.substr(0, buffer.length() - 1);}
WaitForSingleObject(linesRMutex, INFINITE);
resolvedAddresses.push_back(buffer);
ReleaseMutex(linesRMutex);
buffer.clear();
keepFlag = false;
}
}
WaitForSingleObject(linesRCMutex, INFINITE);
++linesResolved;
ReleaseMutex(linesRCMutex);
fileLine.clear();
}
}
}
Please let me know where I am going wrong.
Thanks,
ANkh

Resources