Dukascopy
 
 
Wiki JStore Search Login

Attention! Read the forum rules carefully before posting a topic.

    Try to find an answer in Wiki before asking a question.
    Submit programming questions in this forum only.
    Off topics are strictly forbidden.

Any topics which do not satisfy these rules will be deleted.

closing a FILLED order although getting
 Post subject: closing a FILLED order although getting Post rating: 0   New post Posted: Thu 23 Jun, 2011, 11:44 

User rating: -
Hi,
I am trying to close an order that was filled. this the fill message -
10:09:46 Order FILLED at 1.05279 USD (#93028130 SELL 0.004739 mil. AUD/USD @ MKT MAX SLIPPAGE 0.0005) - Position #22126750

However I am getting an exception as if the order is of state CREATED -

com.dukascopy.api.JFException: state is CREATED
at com.dukascopy.api.impl.connect.PlatformOrderImpl.close(Unknown Source)

Important to mention that I am trying to close the order minutes after it was sent and not a few seconds. so I am absolutely sure the order was filled but for some reason the state I am getting for it is CREATED and therefore cannot close it.

Any suggestions? Thanks.


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Thu 23 Jun, 2011, 11:57 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Do you have a source code which recreates the problem? Or it just occurred once and it does not repeat?


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Thu 23 Jun, 2011, 12:52 

User rating: -
It reoccurs for all symbols after the following scenario -

1. sending a a buy/short order - the order gets filled and also state.FILLED
2. closing an order for the first time since running application - order gets closed and remains state.FILLED (is this OK? shouldnt state change to state.CLOSED?).
3. sending a second buy/short order for the same symbol - the order gets filled but remains state.CREATED and never changes to state.FILLED.

If nessecary I will send the code, but basically its very simple (submitting orders at market only and also closing at market)

Thanks, A


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Thu 23 Jun, 2011, 13:12 

User rating: -
very important -

when I restart the application the state of the order changes from CREATED to FILLED.

does this suggests a connectivity/network/rauter issues?

Should I open certain ports, etc?


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Thu 23 Jun, 2011, 15:42 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
aviavi wrote:
It reoccurs for all symbols after the following scenario -

1. sending a a buy/short order - the order gets filled and also state.FILLED
2. closing an order for the first time since running application - order gets closed and remains state.FILLED (is this OK? shouldnt state change to state.CLOSED?).
3. sending a second buy/short order for the same symbol - the order gets filled but remains state.CREATED and never changes to state.FILLED.

If nessecary I will send the code, but basically its very simple (submitting orders at market only and also closing at market)

Thanks, A

aviavi wrote:
very important -

when I restart the application the state of the order changes from CREATED to FILLED.

does this suggests a connectivity/network/rauter issues?

Should I open certain ports, etc?
It would be very helpful if you could provide a sample strategy which recreates the error that you have described in those 3 steps, since such application behavior is not typical. Additionally please provide the scenario of when do you open and close the application between those steps.


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Fri 24 Jun, 2011, 09:23 

User rating: -
Thank you.
As mention before, order are sent in market, very straight froward, no stop and no target.
when wishing to close I also send a close at market useing engin.getOrder.close(); and failing to close because FILLED orders still hold a CREATED state.

If then I manually stop the java project (from eclipse) and run it again, only then the orders that were FILLED before will get a CLOSED state.
(I also tryied to initialize the IEngine or the IContext, but still the state of the orders that were FILLED remained CREATED (its mind boggling)

ALSO, merge orders also fail (getting an exception saying merge can only be applyed to orders of state FILLED) from the same reason.


Here is the code -


package singlejartest;

public class TSStrategy implements IStrategy {


ArrayList<Position> positions;
ArrayList<Position> closedpositions;

private IEngine engine = null;
private IHistory history;
private IConsole console;
private boolean mergeInProgress = false;
private boolean first = true;


public TSStrategy() {   
positions = new ArrayList<Position>();   
}

public void onStart(IContext context) throws JFException {
engine = context.getEngine();
history = context.getHistory();
this.console = context.getConsole();
console.getOut().println("Started");   

while (true){   
try {
if (first ) first = setPositionState (first);
parseAndSubmit();
Thread.sleep(3000);
engine = null;
engine = context.getEngine();
} catch (InterruptedException e) {
System.out.println("Reading files Thread Exception");   
e.printStackTrace();
}   
}
}



private boolean setPositionState(boolean first) throws JFException {
List<IOrder> allPositions = engine.getOrders();
Double amount=0.0;
//collecting all instruments opened
Map<Instrument, List<IOrder>> allByInstruments = new HashMap<Instrument, List<IOrder>>();
for (IOrder order : allPositions) {
Instrument instr = order.getInstrument();
List<IOrder> orders = allByInstruments.get(instr);
if (orders == null) {
orders = new ArrayList<IOrder>();
allByInstruments.put(instr, orders);
}
orders.add(order);
}

for (Instrument instr : allByInstruments.keySet()) {
List<IOrder> list = allByInstruments.get(instr);

for (IOrder order : list){
if (order.getState()==IOrder.State.FILLED){
if (order.isLong()) {
amount=amount+order.getAmount();
}else{
amount=amount-order.getAmount();
}
}
}   
Position p = new Position(list.get(0).getLabel());
if (amount>0){
p.setType(OrderCommand.BUY);
p.setPositionSize(amount);
p.setInstrument(instr);
}
if (amount<0){
p.setType(OrderCommand.SELL);
p.setPositionSize(amount);
p.setInstrument(instr);
}
amount=0.0;
positions.add(p);
}   
return false;
}



public void parseAndSubmit () throws JFException, InterruptedException {

//parsing files
readfile r = new readfile("TSStrategy 1st test");
r.readFile();

// submitting orders
for (Order rOrder : r.orders) {   
// compare Id with sent orders
for (IOrder order : engine.getOrders(rOrder.symbol)) {
if (order.getLabel().trim().compareToIgnoreCase(rOrder.id)==0) {
rOrder.filled=true;
System.out.println("Order " + rOrder.id + " was already submitted for " + rOrder.symbol);
}
}
Double amount = amountForSymbol(rOrder.symbol);
if (!rOrder.closingPosition&&!rOrder.filled){

// compare desired amount with actual
if (((amount==rOrder.positionSize)&&(rOrder.type.toString().trim().compareToIgnoreCase("Buy")==0))||
((amount==-rOrder.positionSize)&&(rOrder.type.toString().trim().compareToIgnoreCase("Sell")==0)))
rOrder.filled=true;

// entry only if ask < desired for long and bid > price for short
if (rOrder.filled!=true){
Double ask = null;
Double bid = null;
try {
ITick tick = history.getLastTick(rOrder.symbol);
ask = tick.getAsk();
bid = tick.getBid();

if ((rOrder.type.toString().trim().compareToIgnoreCase("Buy")==0)&&(ask!=null)&&(rOrder.price < ask)){
rOrder.filled=true;
System.out.println("Order ignored as Ask > Order Price for " + rOrder.symbol);
}

if ((rOrder.type.toString().trim().compareToIgnoreCase("Sell")==0)&&(bid!=null)&&(rOrder.price > bid)){
rOrder.filled=true;
System.out.println("Order ignored as Bid < Order Price for " + rOrder.symbol);
}   

} catch (Exception e) {
System.out.println("couldn't get last tick for " + rOrder.symbol);
e.printStackTrace();
rOrder.filled=true;
}   

}   

// closing position if amount !=0
}if (rOrder.closingPosition&&!rOrder.filled){
if (amount==0) rOrder.filled=true;
}   

if (!rOrder.filled) submitOrder(rOrder, rOrder.closingPosition);   

}   

}   


private void submitOrder(Order rOrder, Boolean closingPosition) throws JFException, InterruptedException {
Double amount = amountForSymbol(rOrder.symbol);   
IOrder order = getLastOrder(rOrder.symbol);

//closing position
if (closingPosition){
if ((amount != 0)&&(order != null)) {
CloseOrder(order, rOrder);   
}else{
System.out.println("Order ignored as no open positions for " + rOrder.symbol);
rOrder.filled = true;
}   
}else{

//sending entry
if (amount == 0){   
try {
engine.submitOrder(rOrder.id , rOrder.symbol , rOrder.type, rOrder.positionSize);
addPosition(rOrder);
System.out.println("Sending order for " + rOrder.symbol + " " + rOrder.type + " Amount " + rOrder.positionSize);
rOrder.filled = true;
} catch (Exception e) {
System.out.println("Order Submit failed");
e.printStackTrace();
}   
}else{   
if (order != null) CloseOrder(order, rOrder);
try {
engine.submitOrder(rOrder.id , rOrder.symbol , rOrder.type, rOrder.positionSize);
addPosition(rOrder);
System.out.println("Sending order for " + rOrder.symbol + " " + rOrder.type + " Amount " + rOrder.positionSize);
} catch (Exception e) {
System.out.println("Order Submit failed");
e.printStackTrace();
}
}   
}   
}


private void CloseOrder(IOrder order, Order rOrder) {
try {
order.close();
for (Position p : positions){
if (p.getInstrument()==rOrder.symbol) positions.remove(p);
}
System.out.println("Closing position for " + rOrder.symbol + " - order id " + rOrder.id);
} catch (Exception e) {
System.out.println("Closing order FAILED for " + rOrder.symbol + " - order id " + rOrder.id);
e.printStackTrace();
}   
}


private void addPosition(Order rOrder) {
Position p = null;
p.setInstrument(rOrder.symbol);
p.setPositionSize(rOrder.getPositionSize());
p.setType(rOrder.type);

positions.add(p);
}



private void megaMerge() throws JFException {
if (!mergeInProgress) {
List<IOrder> allPositions = engine.getOrders();

//collecting all instrument we have opened
Map<Instrument, List<IOrder>> allByInstruments = new HashMap<Instrument, List<IOrder>>();
for (IOrder order : allPositions) {
Instrument instr = order.getInstrument();
List<IOrder> orders = allByInstruments.get(instr);
if (orders == null) {
orders = new ArrayList<IOrder>();
allByInstruments.put(instr, orders);
}
orders.add(order);
}

//now merging

for (Instrument instr : allByInstruments.keySet()) {
List<IOrder> list = allByInstruments.get(instr);
if (list.size() > 1) {
mergeOrders(list);
mergeInProgress = true;
}
}

}
}

public void mergeOrders(List<IOrder> positions) throws JFException {   
if (positions == null || positions.size() == 0) {
return;
}
engine.mergeOrders("mergeTarget", positions.toArray(new IOrder[0]));   
}



//count open positions
protected int positionsTotal(Instrument instrument) throws JFException {
int counter = 0;   
for (IOrder order : engine.getOrders(instrument)) {
if (order.getState() == IOrder.State.FILLED) {
counter++;   
}
}
return counter;
}


protected Double amountForSymbol(Instrument instrument) throws JFException {   
Double amount = 0.000;   
for (Position p : positions){
if (p.getInstrument()==instrument) {
amount = amount+p.getPositionSize();
}
}
return amount;
}



protected IOrder getLastOrder(Instrument instrument) throws JFException {
if (positionsTotal(instrument) >1){
try {
megaMerge();
} catch (Exception e) {
System.out.println("Mega merge failed");
e.printStackTrace();
}   
}
IOrder order = null;
int orderNum=0;
List<IOrder> orders = ordersPerSymbol(instrument);   
if (orders.size() >0 ) {
order = orders.get(orderNum);
orderNum = orders.size()-1;   
}
return order;
}



protected List<IOrder> ordersPerSymbol(Instrument instrument) throws JFException {
List<IOrder> orders = engine.getOrders(instrument);
for (IOrder order : engine.getOrders(instrument)) {
if ((orders.size() > 0)&&(order.getState() == IOrder.State.CLOSED)) {
orders.remove(order);
}
if ((orders.size() > 0)&&(order.getState() == IOrder.State.CANCELED)) {   
orders.remove(order);
}
if ((orders.size() > 0)&&(order.getClosePrice()!=0)) {   
orders.remove(order);
}   
}
return orders;
}


protected String getLabel(Instrument instrument) {
String label = instrument.name();
label = label.substring(0, 2) + label.substring(3, 5);
//    label = label + (tagCounter++);
label = label.toLowerCase();
return label;
}

public void onMessage(IMessage message) throws JFException {   
//    System.out.println("Trying to read messgaes !!!! ");   
}

public void onAccount(IAccount account) throws JFException {
}

public void onStop() throws JFException {
for (IOrder order : engine.getOrders()) {
order.close();
}
console.getOut().println("Stopped");
}

public void onTick(Instrument instrument, ITick tick) throws JFException {   
}

public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) {
}
}


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Mon 27 Jun, 2011, 10:10 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
The code does not compile - there are no imports or implementation for Position class. As well as there are no imports added in general.


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Wed 29 Jun, 2011, 09:46 

User rating: -
Hi,
My issue is that orders' state does not refresh in real time only when I first launch the Java project.

Example, when I send an order to buy the order get FILLED (I see this in the message box of the JForex UI), however, through the API the state I getting for this order is CREATED (therefore cant close it). this will remain so until I will stop the Java project and only after re-running it I will get the state FILLED for this order. this happens all the time for all symbols preventing me from trading.

I believe this is a communication/data update issue and not a code bug. I made sure that ports given by your support are open 9443, 10443, 9543, 10543. This also reoccurred from my home and from my office (different internet providers).

Here are the other Classes (Position, Order, readfile) -
if you prefer please provide an email adress and I will send you all src files in one rar file.

Thanks in advance, A

package singlejartest;

import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.Instrument;

public class Position {
   
   OrderCommand type;   //of type B, S, T, C
                     //each should have time, date, size driven from a txt file
   Double positionSize;
   String date;
   String time;
   double gain;
   Instrument instrument;
   String name;
   
   public Position(String name) {
      this.name = name;      
   }
   
   
   //getters and setters
   
   public Double getPositionSize() {
      return positionSize;
   }
   public String getDate() {
      return date;
   }
   public String getTime() {
      return time;
   }
   public double getGain() {
      return gain;
   }
   public OrderCommand getType() {
      return type;
   }
   public void setType(OrderCommand type) {
      this.type = type;
   }
   public void setPositionSize(Double positionSize) {
      this.positionSize = positionSize;
   }
   public void setDate(String date) {
      this.date = date;
   }
   public void setTime(String time) {
      this.time = time;
   }
   public void setGain(double gain) {
      this.gain = gain;
   }
   public Instrument getInstrument() {
      return instrument;
   }
   public void setInstrument(Instrument instrument) {
      this.instrument = instrument;
   }   
}


public class Order {
   String id;
   Instrument symbol;
   Double price;
   OrderCommand type;   //of type B, S, T, C
   Boolean filled = false;                  
   Double positionSize;
   String date;
   String time;
   String filename;
   Boolean closingPosition;
   
   public Boolean getFilled() {
      return filled;
   }

   public void setFilled(Boolean filled) {
      this.filled = filled;
   }

   public Boolean getClosingPosition() {
      return closingPosition;
   }

   public void setClosingPosition(Boolean closingPosition) {
      this.closingPosition = closingPosition;
   }

   public void setPositionSize(Double positionSize) {
      this.positionSize = positionSize;
   }

   public Order(){
      this.filled = false;
   }
   
      //getters
   public Instrument getSymbol() {
      return symbol;
   }
   public void setSymbol(Instrument instrument) {
      this.symbol = instrument;
   }
      
   public Double getPrice() {
      return price;
   }
   public OrderCommand getType() {
      return type;
   }
   public Double getPositionSize() {
      return positionSize;
   }
   public String getDate() {
      return date;
   }
   public String getTime() {
      return time;
   }
   
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getFilename() {
      return filename;
   }
   public void setFilename(String filename) {
      this.filename = filename;
   }
   public void setType(OrderCommand type) {
      this.type = type;
   }
   public void setPositionSize(double d) {
      this.positionSize = d;
   }
   public void setDate(String date) {
      this.date = date;
   }
   public void setTime(String time) {
      this.time = time;
   }
   
   public void addLine(String line, String delimiter) {
      
   }
   public void setPrice(double d) {
      this.price = d;      
   }
}


import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.Instrument;


public class readfile {
   
   ArrayList<Order> orders;
   ArrayList<Symbol> symbols;
   String name;
   
   
   public readfile(String name) {
      this.name = name;
      orders = new ArrayList<Order>();
      symbols = new ArrayList<Symbol>();
   }

   public ArrayList<Order> getOrder() {
      return orders;
   }

   public ArrayList<Symbol> getSymbol() {
      return symbols;
   }

   public String getName() {
      return name;
   }

   public void addOrder(Order o1) {
      this.orders.add(o1);
      
   }

   public void removeOrder(Order o1) {
      this.orders.remove(o1);
      
   }
   
   public void addSymbol(Symbol s1) {
      this.symbols.add(s1);
      
   }
   
   public void removeSymbol(Symbol s1) {
      this.symbols.remove(s1);
      
   }
   
   
   static String listFilenames;
   
   public void readFile() {
      File directory = new File ("C:/Documents and Settings/Administrator/TS Log");      
      String delimiter = ",";
      String filename[] = directory.list();
      Scanner x = null;
      String beforeLastLine = null;
      String lastLine = null;
      
      
            
      // parsing files
      for (int i = 0; i < filename.length; i++) {
         
         listFilenames = filename[i];
         System.out.println("Reading file " + listFilenames + " file no. " + (i+1) + " out of " + filename.length);
         System.out.println(directory + "/" + listFilenames);         
         try{
            x = new Scanner (new File(directory + "/" + listFilenames));
         }
         catch (Exception ex){
            System.out.println("Could not find file");
         }
         
         try {
            while (x.hasNext()) {
               lastLine = x.next();
            }
         }
         catch (Exception e) {
            System.out.println("Error in reading txt file "+listFilenames);
            lastLine = beforeLastLine;            
         }
         System.out.printf("%s\n", lastLine);
         
         
         Order lastOrder = new Order ();
         String[] array = lastLine.split(delimiter);
         
         if(array.length != 7){
            System.out.println("List Error in txt file "+listFilenames);
         }
         Symbol lastSymbol = new Symbol();         

         lastOrder.setId(array[1].substring(0, 2)+array[1].substring(3, 5)+array[4].substring(0, 2)+array[0]);
         lastOrder.setClosingPosition(array[4].toLowerCase().trim().compareTo("cover")==0 || array[4].toLowerCase().trim().compareTo("sell")==0 );
         lastOrder.setSymbol(ParseInstrument(array[1]));
         lastOrder.setDate(array[2]);
         lastOrder.setTime(array[3]);
         lastOrder.setType(ParseOrderType(array[4]));
         lastOrder.setPositionSize(ParseAmount(array[5]));
         lastOrder.setPrice(Double.parseDouble(array[6]));
         lastOrder.setFilename(listFilenames);
                  
         orders.add(lastOrder);
                  
         lastSymbol.currency = lastOrder.getSymbol();
         symbols.add(lastSymbol);
         
         x.close();
      }
   
      System.out.println("End of ReadFile method");
   }

   private OrderCommand ParseOrderType(String str)
   {      
      System.out.println("*** Order Type !" + str + "!");
      str=str.toLowerCase().trim();
      
      if (str.compareTo("buy")==0 || str.compareTo("cover")==0){
         return OrderCommand.BUY;
      }
      else
      {
         return OrderCommand.SELL;   
      }         
   }
   
   private Instrument ParseInstrument(String str)
   {
      str = str.substring(0, 3)+ "/" + str.substring(3, 6);
      System.out.println("Parsing Instrument " + str);
      return Instrument.fromString(str);
   }   
   
   private Double ParseAmount(String str)
   {
      
      Double amount = Double.parseDouble(str);
      if (amount<1000) {
         System.out.println("Amount has been increased to a minimum of $1000");
         amount=1000.0/1000000;
      }
      else{
         amount=amount/1000000;
      }
      return amount;
   }   
}


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Wed 29 Jun, 2011, 13:07 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Probably the states don't update because your class Order does not hold a reference to the corresponding IOrder, but basically does all the updates "by hand". Essentially you are keeping the same values in two separate objects and try to keep them synchronized which is rather a tedious and error-prone routine. If you find using a wrapper class necessary, consider keeping a reference of an IOrder and using this reference as much as possible, for example:
class OrderWrapper {
   private IOrder order;

   public IOrder getOrder() { return order; }
   public void setOrder(IOrder order) { this.order = order; }
   
   //do this instead of keeping a separate field Boolean filled 
   public Boolean getFilled() {
      return order.getState() == IOrder.State.FILLED;
   }
   
   //equivalent to this.getOrder().getInstrument()
   public Instrument getSymbol() {
      return order.getInstrument();
   }
   
   //etc.
}
Also there is no clear necessity why keep your orders in file since IEngine.getOrders() returns list of orders in CREATED, OPENED and FILLED state regardless in which session those orders were created.
Also note that TSStrategy.ordersPerSymbol essentially returns the same list of orders as as IEngine.getOrders.


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Wed 29 Jun, 2011, 14:27 

User rating: -
Thank you.

I guess I wasnt clear about the process -
Another SW is analysing the data and print to txt file in real time orders for each symbol (buy, sell, short, cover).

Then I parse these txt files (using the readFile method in readfile class) and send orders accordingly. Class order holds the last order recieved for each symbol from the txt file.

I am using
List<IOrder> allPositions = engine.getOrders();
to compare with desired position in txt file (i.e. class Order).

However, after an order was sent and filled when using engine.getOrders(); I get a CREATED state for this order. Only after stopping and rerunning the state will be FILLED. I tried and by pass this obsticale by creating the Position class (similar to the OrderWrapper). this was good for monitoring the position but when I tried and use order.close(); I got an exception that I order is of state CREATED and close(); could be applyed only on order state FILLED.

PLEASE help me overcome this. Thank you in advance, A


 
 Post subject: Re: closing a FILLED order although getting Post rating: 0   New post Posted: Wed 29 Jun, 2011, 15:18 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
aviavi wrote:
However, after an order was sent and filled when using engine.getOrders(); I get a CREATED state for this order. Only after stopping and rerunning the state will be FILLED. I tried and by pass this obsticale by creating the Position class (similar to the OrderWrapper). this was good for monitoring the position but when I tried and use order.close(); I got an exception that I order is of state CREATED and close(); could be applyed only on order state FILLED.
Have you considered using IOrder.waitForUpdate(time millis)? For example:
      IOrder order1 = engine.submitOrder("myOrder", Instrument.EURUSD, OrderCommand.BUY, 0.01);
      order1.waitForUpdate(1000);
      console.getOut().println(order1.getState());
By having all those wrapper and file handling classes it's rather complicated to locate the reason of the problem. It would be much easier to assist you if you could provide a smaller example which recreates the same behavior.


 

Jump to:  

  © 1998-2025 Dukascopy® Bank SA
On-line Currency forex trading with Swiss Forex Broker - ECN Forex Brokerage,
Managed Forex Accounts, introducing forex brokers, Currency Forex Data Feed and News
Currency Forex Trading Platform provided on-line by Dukascopy.com