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.

How to send an order command from 1 platform to other platforms
 Post subject: How to send an order command from 1 platform to other platforms Post rating: 0   New post Posted: Mon 20 Apr, 2015, 00:43 
User avatar

User rating: 1
Joined: Fri 22 Mar, 2013, 12:09
Posts: 9
Location: Italy, Florence
hi
i want to build a widget displyed on any forex chart, in this widget there is a buy button, when i press it i want to make a buy order AND to make the same buy order in other jforex platform. In other words i have 2 or more jforex platform and i want to open 1 order on 1 platform and automatically, this orderd is copied to the other platforms

I write this code:

//spinner
//https://www.java2s.com/Tutorial/Java/0240__Swing/SpinnerNumberModel.htm
package com.dukascopy.strategy;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;

import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IChart;
import com.dukascopy.api.IConsole;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IEngine;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IOrder;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.Period;
import com.dukascopy.api.drawings.ICustomWidgetChartObject;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.JFAuthenticationException;

public class OrderManagerWidget implements IStrategy {
   private IContext context;
   private IEngine engine;
   private IConsole console;
   private Set<MyWidget> widgets = new HashSet<>();

   @Override
   public void onStart(final IContext context) throws JFException {
      this.context = context;
      this.engine = context.getEngine();
      this.console = context.getConsole();

      final Set<IChart> charts = context.getCharts();
      if (charts == null) {
         context.getConsole().getErr().println("No chart opened!");
         context.stop();
      }

      for (Object object : charts) {
         final IChart chart = (IChart) object;
         widgets.add(new MyWidget(chart));

      }

   }

   public void onTick(Instrument instrument, ITick tick) throws JFException {
      try {
         for (MyWidget w : widgets) {
            if (w.chart.getInstrument().equals(instrument)) {
               w.updateLabel(instrument, tick);
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void onMessage(IMessage message) throws JFException {
   }

   public void onAccount(IAccount account) throws JFException {
   }

   public void onStop() throws JFException {
      final Set<IChart> charts = context.getCharts();
      if (charts == null) {
         context.getConsole().getErr().println("No chart opened!");
         context.stop();
      }

      for (Object object : charts) {
         IChart chart = (IChart) object;

         chart.remove("ScalpWidget");
      }
   }

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

   class MyWidget {
      final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      IChart chart;

      ICustomWidgetChartObject obj;

      MyWidget(IChart pchart) {
         this.chart = pchart;
         Instrument instrument = chart.getInstrument();

         JButton buttonBuy = new JButton("Buy") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void paintComponent(Graphics g) {
               super.paintComponent(g);
               g.setColor(new Color(205, 229, 198, 60));
               g.fillRect(0, 0, getWidth(), getHeight());
            }
         };
         buttonBuy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               context.executeTask(new Callable<IOrder>() {
                  @Override
                  public IOrder call() throws Exception {
                     return buy();
                  }

               });
            }
         });

         /********/

         obj = chart.getChartObjectFactory().createChartWidget("ScalpWidget");
         obj.setText("Scalp Manager " + instrument.toString().toUpperCase());

         obj.setFillOpacity(0.1f); // use 0f for transparent chart widget
         obj.setColor(new Color(17, 126, 17));
         obj.setFillColor(new Color(64, 64, 64));

         Dimension dBuySell = new Dimension(77, 38);
         Font font = new Font("default", Font.BOLD, 12);

         buttonBuy.setSize(dBuySell);
         buttonBuy.setMinimumSize(dBuySell);
         buttonBuy.setMaximumSize(dBuySell);
         buttonBuy.setPreferredSize(dBuySell);
         buttonBuy.setForeground(new Color(0, 60, 0));
         buttonBuy.setFont(font);
         buttonBuy.setBorderPainted(false);



         JPanel panel = obj.getContentPanel();
         panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

         panel.add(buttonBuy);

         int height = 236;
         panel.setSize(new Dimension(190, height));// width*hight
         panel.setMinimumSize(new Dimension(190, height));
         panel.setMaximumSize(new Dimension(190, height));
         panel.setBorder(new EmptyBorder(4, 4, 4, 4));


         chart.add(obj);
      }


      IOrder buy() throws JFException {
         Instrument instrument = chart.getInstrument();
         ITick lastITick = context.getHistory().getLastTick(instrument);
         double lastTickAskValue = lastITick.getAsk();
         Double currentAmount = 0.001;
         IOrder iorder = context.getEngine().submitOrder("green" + System.currentTimeMillis(), instrument,
               OrderCommand.BUY, currentAmount);

         if (iorder != null) {
            iorder.waitForUpdate(2000);
            console.getOut()
                  .println(
                        String.format(
                              "ScalpWidget - %s - %s - ask side, buy price: %s - time: %s - amount: %s - slippage: %,1.4f",
                              instrument, iorder.getLabel(), iorder.getOpenPrice(),
                              sdf.format(System.currentTimeMillis()), currentAmount,
                              Math.abs(lastTickAskValue - iorder.getOpenPrice())));
         }
         
         /*************************************************************************************************/
         String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
           IClient client;
         try {
            client = ClientFactory.getDefaultInstance();
            client.connect(jnlpUrl, "myUserOfSecondPlatform", "myPwdOfSecondPlatform");
            console.getOut().println("client connect succesfull");
            client.startStrategy(this.new BuyStrat(currentAmount, instrument));
         } catch (Exception e) {
            console.getOut().println("Exception: " + e.getMessage());
         }

         return iorder;
      }
      
       public class BuyStrat implements IStrategy {
          
          double currentAmount = 0;
          Instrument instrument = null;
          
           public BuyStrat (double currentAmount, Instrument instrument) {
              this.currentAmount = currentAmount;
              this.instrument = instrument;
           }
   
           public void onAccount(IAccount account) throws JFException {}
   
           public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar)
                   throws JFException {}
   
           public void onMessage(IMessage message) throws JFException {}
   
           public void onStart(IContext context) throws JFException {
               subscriptionInstrumentCheck(instrument);
               IOrder iorder = context.getEngine().submitOrder("order" + System.currentTimeMillis(), instrument,
                  OrderCommand.BUY, currentAmount);
            if (iorder != null)
               iorder.waitForUpdate(2000);
            else
               console.getOut().println("order null");
              
              
           }
   
           public void onStop() throws JFException {}
   
           public void onTick(Instrument instrument, ITick tick) throws JFException {
              
           }
          
          public void subscriptionInstrumentCheck(Instrument instrument) {
             try {
                if (!context.getSubscribedInstruments().contains(instrument)) {
                   Set<Instrument> instruments = new HashSet<Instrument>();
                   instruments.add(instrument);
                   context.setSubscribedInstruments(instruments, true);
                   Thread.sleep(100);
                }
             } catch (InterruptedException e) {
                e.printStackTrace();
             }
          }
       }
      void updateLabel(Instrument instrument, ITick tick) throws JFException {
         obj.setText("Scalp Manager " + chart.getInstrument().toString().toUpperCase());

      }

   }

}


In my code, i use the class BuyStrat to buy a position in a second forex platform
If i run and i click on buy button, i get this error message:
2015-04-20 01:28:50.496 ERROR AuthorizationClient - access denied ("java.util.PropertyPermission" "server.region" "read")
java.security.AccessControlException: access denied ("java.util.PropertyPermission" "server.region" "read")


this is the stacktrace:
2015-04-20 01:28:50.398 DEBUG bu - Submitting order [<OrderGroupMessage(,instrument=EUR/JPY,orders=[<OrderMessageExt(hsexUser=false,executorBlackList=[],boCancelReplace=false,primeBroker=[],wlFilter=false,wlVirtual=false,reverse=false,locked=false,skipRepeat=false,bidOfferCancellReplace=false,properties=[],instrument=EUR/JPY,amount=1000.000,side=BUY,priceTrailingLimit=0.05,priceClient=128.442,direction=OPEN,oco=false,state=CREATED,trades=[],placeOffer=false,mcOrder=false,externalSysId=green1429486130398,strategyId=OrderManagerWidget.jfx D2B3B93E0104D7D92EB600BD813DFF75,rollover=false,fillOrKill=false,immediateOrCancel=false,sessionId=9028db48-6665-4767-bb70-3e9cdfed8721,strategyType=0,trailSLandTP=false,init=false,internalIp=192.168.1.3,externalIp=93.149.232.216,managerType=TRADER)>],ocoMerge=false,mc=false,externalSysId=green1429486130398,real=false,init=false,managerType=TRADER,timestamp=1429486130398)>]
Order BUY 1000 EUR/JPY @ MKT  is sent at 2015-04-19 23:28:50.401 GMT by the strategy "OrderManagerWidget": from the local computer
2015-04-20 01:28:50.464 DEBUG PlatformOrderImpl - processing OrderGroupMessage [<OrderGroupMessage(orderGroupId=81750143,instrument=EUR/JPY,orders=[<OrderMessageExt(hsexUser=false,executorBlackList=[],boCancelReplace=false,primeBroker=[],wlFilter=false,wlVirtual=false,reverse=false,equity=6152.49,locked=false,skipRepeat=false,bidOfferCancellReplace=false,properties=[],orderId=310494248,instrument=EUR/JPY,amount=1000,side=BUY,priceTrailingLimit=0.05,priceClient=128.442,orderGroupId=81750143,direction=OPEN,oco=false,state=EXECUTING,trades=[],notes=,placeOffer=false,parentOrderId=310494248,createdDate=Sun Apr 19 23:28:48 UTC 2015,mcOrder=false,externalSysId=green1429486130398,strategyId=OrderManagerWidget.jfx D2B3B93E0104D7D92EB600BD813DFF75,rollover=false,fillOrKill=false,immediateOrCancel=false,sessionId=9028db48-6665-4767-bb70-3e9cdfed8721,strategyType=0,trailSLandTP=false,bestBid=128.435,bestAsk=128.442,checkTime=1429486128868,init=false,internalIp=192.168.1.3,externalIp=93.149.232.216,platform=DDS3_JFOREX,managerType=TRADER,ts=1429486128867,userId=816911,accountLoginId=773335,timestamp=1429486128868)>],amount=0,pricePosOpen=0,side=LONG,status=OPEN,ocoMerge=false,mc=false,externalSysId=green1429486130398,real=false,accCcy=EUR,init=false,platform=DDS3_JFOREX,managerType=TRADER,ts=1429486128867,userId=816911,accountLoginId=773335,timestamp=1429486128874)>]
2015-04-20 01:28:50.465 DEBUG PlatformOrderImpl - transiting order from CREATED state to OPENED as a response to EXECUTING order update message
2015-04-20 01:28:50.496 ERROR AuthorizationClient - access denied ("java.util.PropertyPermission" "server.region" "read")
java.security.AccessControlException: access denied ("java.util.PropertyPermission" "server.region" "read")
   at java.security.AccessControlContext.checkPermission(Unknown Source)
   at java.security.AccessController.checkPermission(Unknown Source)
   at java.lang.SecurityManager.checkPermission(Unknown Source)
   at com.sun.javaws.security.JavaWebStartSecurity.checkPermission(Unknown Source)
   at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
   at java.lang.System.getProperty(Unknown Source)
   at com.dukascopy.api.impl.connect.AuthorizationClient.a(Unknown Source)
   at com.dukascopy.api.impl.connect.DCClientImpl.a(Unknown Source)
   at com.dukascopy.api.impl.connect.DCClientImpl.connect(Unknown Source)
   at com.dukascopy.api.impl.connect.DCClientImpl.connect(Unknown Source)
   at com.dukascopy.strategy.OrderManagerWidget$MyWidget.buy(OrderManagerWidget.java:208)
   at com.dukascopy.strategy.OrderManagerWidget$MyWidget$2$1.call(OrderManagerWidget.java:139)
   at com.dukascopy.strategy.OrderManagerWidget$MyWidget$2$1.call(OrderManagerWidget.java:1)
   at com.dukascopy.api.impl.execution.k.call(Unknown Source)
   at java.util.concurrent.FutureTask.run(Unknown Source)
   at com.dukascopy.api.impl.execution.g$a.f(Unknown Source)
   at com.dukascopy.api.impl.execution.g$a.run(Unknown Source)
   at java.lang.Thread.run(Unknown Source)
2015-04-20 01:28:50.497 DEBUG DCClientImpl -
2015-04-20 01:28:50.497 DEBUG PlatformOrderImpl - processing OrderGroupMessage [<OrderGroupMessage(orderGroupId=81750143,instrument=EUR/JPY,orders=[<OrderMessageExt(hsexUser=false,executorBlackList=[],zlPresent=128.4385,zlOnReceive=128.4385,commonId=310494248,boCancelReplace=false,primeBroker=[],wlFilter=false,wlVirtual=false,reverse=false,allowSdex=1,wlPartnerId=1,equity=6152.49,locked=false,skipRepeat=false,bidOfferCancellReplace=false,properties=[],orderId=310494248,rootOrderId=310494248,instrument=EUR/JPY,amount=1000.00,side=BUY,priceTrailingLimit=0.05,priceClient=128.442,priceClientInitial=128.442,orderGroupId=81750143,direction=OPEN,oco=false,state=FILLED,trades=[],notes=,placeOffer=false,parentOrderId=310494248,createdDate=Sun Apr 19 23:28:48 UTC 2015,mcOrder=false,externalSysId=green1429486130398,strategyId=OrderManagerWidget.jfx D2B3B93E0104D7D92EB600BD813DFF75,rollover=false,pricePosOpen=128.442,origAmount=1000.00,fillOrKill=false,immediateOrCancel=false,sessionId=9028db48-6665-4767-bb70-3e9cdfed8721,orderCommission=0.03,strategyType=0,execAmount=1000.00,execPrice=128.442,routerExecTime=Sun Apr 19 23:28:48 UTC 2015,accCcy=EUR,trailSLandTP=false,bestBid=128.435,bestAsk=128.442,checkTime=1429486128869,init=false,internalIp=192.168.1.3,externalIp=93.149.232.216,platform=DDS3_JFOREX,managerType=TRADER,ts=1429486128875,userId=816911,accountLoginId=773335,timestamp=1429486128875)>],summaryCommission=0.03,amount=1000.00,priceOpen=128.442,pricePosOpen=128.442,side=LONG,status=OPEN,ocoMerge=false,mc=false,externalSysId=green1429486130398,real=false,accCcy=EUR,pricePosOrig=128.442,init=false,platform=DDS3_JFOREX,managerType=TRADER,ts=1429486128867,userId=816911,accountLoginId=773335,timestamp=1429486128878)>]
2015-04-20 01:28:50.497 DEBUG PlatformOrderImpl - transiting order from OPENED to FILLED state as a response to FILLED order update message



Where is the error in my code?


 
 Post subject: Re: How to send an order command from 1 platform to other platforms Post rating: 0   New post Posted: Fri 24 Apr, 2015, 14:52 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Strategy can use sockets as described here: https://www.dukascopy.com/wiki/#Socket_Channel
Lets say that there are two JForex clients open for two accounts.
Main client instance has a chart open with the buy widget that you have provided. This widget needs to use SocketClient to send data to the second client.
Second JForex application needs to run Socket server in the form of SocketStrategy. SocketStrategy receives messages from the SocketClient and opens new positions.


 

Jump to:  

cron
  © 1998-2024 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