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.

Use of Leverage
 Post subject: Use of Leverage Post rating: 1   New post Posted: Fri 15 Jun, 2018, 06:56 

User rating: 3
Joined: Sat 09 Jun, 2018, 03:18
Posts: 24
Location: China,
Does the Backtest program will adjust the leverage limit to 1:30 on weekends?


 
 Post subject: Re: Use of Leverage Post rating: 0   New post Posted: Fri 15 Jun, 2018, 11:26 
User avatar

User rating: 13
Joined: Mon 27 Jul, 2015, 16:30
Posts: 110
Location: Canada, Mission
Yes, it can be done!


 
 Post subject: Re: Use of Leverage Post rating: 1   New post Posted: Fri 15 Jun, 2018, 15:47 

User rating: 3
Joined: Sat 09 Jun, 2018, 03:18
Posts: 24
Location: China,
JP7 wrote:
No, I don't think so!
You can change the Leverage to 30 for all tested period, to see if the strategy is successful in this conditions.



Ok,thanks


 
 Post subject: Re: Use of Leverage Post rating: 1   New post Posted: Mon 25 Jun, 2018, 14:30 
User avatar

User rating: 13
Joined: Mon 27 Jul, 2015, 16:30
Posts: 110
Location: Canada, Mission
I rectify my statement, Yes is possible change to weekend leverage in the strategy but I have to study more and will take more time !


Meanwhile you can test your strategy with this little tool.
When Use of Leverage reaches 30% the strategy will close all trades and shuts down, so will not pass weekend leverage restrictions if happens.
You have to imbedded in your strategy to run demo testing, if you need help with that let me know ….

Cheers JP7 ;)

///By JP7 from Dukascopy Forum///

import com.dukascopy.api.*;
import java.text.DecimalFormat;

public class UseofLeverage_Percentage_Closure implements IStrategy {


    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    @Configurable("Use of Leverage drop % closure")
    public double tpPercent = 30.00;

    private double balance;
   

    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.setHistory(context.getHistory());
        context.getConsole();// on start
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;

        // remove this line with // after testing
        engine.submitOrder("ord1", Instrument.EURUSD, IEngine.OrderCommand.SELL, 0.7); //
        //
       
        balance = context.getAccount().getEquity();
        console.getOut().println("initial balance "+(new DecimalFormat("#.#######")).format(balance));
       
    }

    public void onAccount(IAccount account) throws JFException {
 
        double UseofLeverage = account.getUseOfLeverage();

        console.getOut().println("UseofLeverage"+(UseofLeverage));

       
        if (UseofLeverage >= tpPercent) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                    console.getOut().println("Leverage % Reached "+(UseofLeverage)+" %");

                }
            }
           
            balance = account.getEquity();
            console.getOut().println("Use of Leverage % Reached "+(new DecimalFormat("#.#######")).format(balance));
                    context.stop();
        }
       
    }


    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

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

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

    public IHistory getHistory() {
        return history;
    }

    public void setHistory(IHistory history) {
        this.history = history;
    }
    public void setContext(IContext context) {
        this.context = context;
    }

}


Attachments:
UseofLeverage_Percentage_Closure.java [2.45 KiB]
Downloaded 195 times
DISCLAIMER: Dukascopy Bank SA's waiver of responsability - Documents, data or information available on this webpage may be posted by third parties without Dukascopy Bank SA being obliged to make any control on their content. Anyone accessing this webpage and downloading or otherwise making use of any document, data or information found on this webpage shall do it on his/her own risks without any recourse against Dukascopy Bank SA in relation thereto or for any consequences arising to him/her or any third party from the use and/or reliance on any document, data or information found on this webpage.
 
 Post subject: Re: Use of Leverage Post rating: 1   New post Posted: Fri 29 Jun, 2018, 13:33 

User rating: 3
Joined: Sat 09 Jun, 2018, 03:18
Posts: 24
Location: China,
JP7 wrote:
I rectify my statement, Yes is possible change to weekend leverage in the strategy but I have to study more and will take more time !


Meanwhile you can test your strategy with this little tool.
When Use of Leverage reaches 30% the strategy will close all trades and shuts down, so will not pass weekend leverage restrictions if happens.
You have to imbedded in your strategy to run demo testing, if you need help with that let me know ….

Cheers JP7 ;)

///By JP7 from Dukascopy Forum///

import com.dukascopy.api.*;
import java.text.DecimalFormat;

public class UseofLeverage_Percentage_Closure implements IStrategy {


    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    @Configurable("Use of Leverage drop % closure")
    public double tpPercent = 30.00;

    private double balance;
   

    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.setHistory(context.getHistory());
        context.getConsole();// on start
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;

        // remove this line with // after testing
        engine.submitOrder("ord1", Instrument.EURUSD, IEngine.OrderCommand.SELL, 0.7); //
        //
       
        balance = context.getAccount().getEquity();
        console.getOut().println("initial balance "+(new DecimalFormat("#.#######")).format(balance));
       
    }

    public void onAccount(IAccount account) throws JFException {
 
        double UseofLeverage = account.getUseOfLeverage();

        console.getOut().println("UseofLeverage"+(UseofLeverage));

       
        if (UseofLeverage >= tpPercent) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                    console.getOut().println("Leverage % Reached "+(UseofLeverage)+" %");

                }
            }
           
            balance = account.getEquity();
            console.getOut().println("Use of Leverage % Reached "+(new DecimalFormat("#.#######")).format(balance));
                    context.stop();
        }
       
    }


    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

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

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

    public IHistory getHistory() {
        return history;
    }

    public void setHistory(IHistory history) {
        this.history = history;
    }
    public void setContext(IContext context) {
        this.context = context;
    }

}




Thanks for your help!


 
 Post subject: Re: Use of Leverage Post rating: 0   New post Posted: Sat 21 Sep, 2019, 06:54 
User avatar

User rating: 13
Joined: Mon 27 Jul, 2015, 16:30
Posts: 110
Location: Canada, Mission
example of strategy calling OverWeekendEndLeverage = account.getOverWeekEndLeverage(); (line 85)

package com.dukascopy.visualforex.visualjforex;

import java.util.*;
import com.dukascopy.api.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.CopyOnWriteArrayList;
import java.lang.reflect.*;
import java.math.BigDecimal;


/*
 * Created by VisualJForex Generator, version 2.35
 * Date: 05.01.2017 15:22
 */
public class untitledStrategy1 implements IStrategy {

    private CopyOnWriteArrayList<TradeEventAction> tradeEventActions = new CopyOnWriteArrayList<TradeEventAction>();
    private static final String DATE_FORMAT_NOW = "yyyyMMdd_HHmmss";
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;

    @Configurable("defaultSlippage:")
    public int defaultSlippage = 5;
    @Configurable("defaultTakeProfit:")
    public int defaultTakeProfit = 50;
    @Configurable("defaultTradeAmount:")
    public double defaultTradeAmount = 0.001;
    @Configurable("defaultPeriod:")
    public Period defaultPeriod = Period.TEN_MINS;
    @Configurable("defaultStopLoss:")
    public int defaultStopLoss = 25;
    @Configurable("defaultInstrument:")
    public Instrument defaultInstrument = Instrument.EURUSD;

    private double UseofLeverage;
    private String AccountCurrency = "";
    private List<IOrder> PendingPositions =  null ;
    private double Leverage;
    private List<IOrder> AllPositions =  null ;
    private Candle LastAskCandle =  null ;
    private int MarginCutLevel;
    private int OverWeekendEndLeverage;
    private Tick LastTick =  null ;
    private boolean GlobalAccount;
    private List<IOrder> OpenPositions =  null ;
    private IMessage LastTradeEvent =  null ;
    private Candle LastBidCandle =  null ;
    private String AccountId = "";
    private double Equity;


    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;
        this.indicators = context.getIndicators();
        this.userInterface = context.getUserInterface();

        subscriptionInstrumentCheck(defaultInstrument);

        ITick lastITick = context.getHistory().getLastTick(defaultInstrument);
        LastTick = new Tick(lastITick, defaultInstrument);

        IBar bidBar = context.getHistory().getBar(defaultInstrument, defaultPeriod, OfferSide.BID, 1);
        IBar askBar = context.getHistory().getBar(defaultInstrument, defaultPeriod, OfferSide.ASK, 1);
        LastAskCandle = new Candle(askBar, defaultPeriod, defaultInstrument, OfferSide.ASK);
        LastBidCandle = new Candle(bidBar, defaultPeriod, defaultInstrument, OfferSide.BID);

        subscriptionInstrumentCheck(Instrument.fromString("EUR/USD"));

    }

    public void onAccount(IAccount account) throws JFException {
        AccountCurrency = account.getCurrency().toString();
        Leverage = account.getLeverage();
        AccountId= account.getAccountId();
        Equity = account.getEquity();
        UseofLeverage = account.getUseOfLeverage();
        OverWeekendEndLeverage = account.getOverWeekEndLeverage();
        MarginCutLevel = account.getMarginCutLevel();
        GlobalAccount = account.isGlobal();
    }

    private void updateVariables(Instrument instrument) {
        try {
            AllPositions = engine.getOrders();
            List<IOrder> listMarket = new ArrayList<IOrder>();
            for (IOrder order: AllPositions) {
                if (order.getState().equals(IOrder.State.FILLED)){
                    listMarket.add(order);
                }
            }
            List<IOrder> listPending = new ArrayList<IOrder>();
            for (IOrder order: AllPositions) {
                if (order.getState().equals(IOrder.State.OPENED)){
                    listPending.add(order);
                }
            }
            OpenPositions = listMarket;
            PendingPositions = listPending;
        } catch(JFException e) {
            e.printStackTrace();
        }
    }

    public void onMessage(IMessage message) throws JFException {
        if (message.getOrder() != null) {
            updateVariables(message.getOrder().getInstrument());
            LastTradeEvent = message;
            for (TradeEventAction event :  tradeEventActions) {
                IOrder order = message.getOrder();
                if (order != null && event != null && message.getType().equals(event.getMessageType())&& order.getLabel().equals(event.getPositionLabel())) {
                    Method method;
                    try {
                        method = this.getClass().getDeclaredMethod(event.getNextBlockId(), Integer.class);
                        method.invoke(this, new Integer[] {event.getFlowId()});
                    } catch (SecurityException e) {
                            e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                          e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    tradeEventActions.remove(event);
                }
            }   
        }
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        LastTick = new Tick(tick, instrument);
        updateVariables(instrument);

            OpenatMarket_block_10(0);

    }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        LastAskCandle = new Candle(askBar, period, instrument, OfferSide.ASK);
        LastBidCandle = new Candle(bidBar, period, instrument, OfferSide.BID);
        updateVariables(instrument);

    }

    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();
          }
        }

    public double round(double price, Instrument instrument) {
        BigDecimal big = new BigDecimal("" + price);
        big = big.setScale(instrument.getPipScale() + 1, BigDecimal.ROUND_HALF_UP);
        return big.doubleValue();
    }

    public ITick getLastTick(Instrument instrument) {
        try {
            return (context.getHistory().getTick(instrument, 0));
        } catch (JFException e) {
             e.printStackTrace(); 
         }
         return null;
    }

    private  void OpenatMarket_block_10(Integer flow) {
        Instrument argument_1 = defaultInstrument;
        double argument_2 = defaultTradeAmount;
        int argument_3 = defaultSlippage;
        int argument_4 = defaultStopLoss;
        int argument_5 = defaultTakeProfit;
        String argument_6 = "";
        ITick tick = getLastTick(argument_1);

        IEngine.OrderCommand command = IEngine.OrderCommand.BUY;

        double stopLoss = tick.getBid() - argument_1.getPipValue() * argument_4;
        double takeProfit = round(tick.getBid() + argument_1.getPipValue() * argument_5, argument_1);
       
           try {
               String label = getLabel();           
               IOrder order = context.getEngine().submitOrder(label, argument_1, command, argument_2, 0, argument_3,  stopLoss, takeProfit, 0, argument_6);
                } catch (JFException e) {
            e.printStackTrace();
        }
    }

class Candle  {

    IBar bar;
    Period period;
    Instrument instrument;
    OfferSide offerSide;

    public Candle(IBar bar, Period period, Instrument instrument, OfferSide offerSide) {
        this.bar = bar;
        this.period = period;
        this.instrument = instrument;
        this.offerSide = offerSide;
    }

    public Period getPeriod() {
        return period;
    }

    public void setPeriod(Period period) {
        this.period = period;
    }

    public Instrument getInstrument() {
        return instrument;
    }

    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }

    public OfferSide getOfferSide() {
        return offerSide;
    }

    public void setOfferSide(OfferSide offerSide) {
        this.offerSide = offerSide;
    }

    public IBar getBar() {
        return bar;
    }

    public void setBar(IBar bar) {
        this.bar = bar;
    }

    public long getTime() {
        return bar.getTime();
    }

    public double getOpen() {
        return bar.getOpen();
    }

    public double getClose() {
        return bar.getClose();
    }

    public double getLow() {
        return bar.getLow();
    }

    public double getHigh() {
        return bar.getHigh();
    }

    public double getVolume() {
        return bar.getVolume();
    }
}
class Tick {

    private ITick tick;
    private Instrument instrument;

    public Tick(ITick tick, Instrument instrument){
        this.instrument = instrument;
        this.tick = tick;
    }

    public Instrument getInstrument(){
       return  instrument;
    }

    public double getAsk(){
       return  tick.getAsk();
    }

    public double getBid(){
       return  tick.getBid();
    }

    public double getAskVolume(){
       return  tick.getAskVolume();
    }

    public double getBidVolume(){
        return tick.getBidVolume();
    }

   public long getTime(){
       return  tick.getTime();
    }

   public ITick getTick(){
       return  tick;
    }
}

    protected String getLabel() {
        String label;
        label = "IVF" + getCurrentTime(LastTick.getTime()) + generateRandom(10000) + generateRandom(10000);
        return label;
    }

    private String getCurrentTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(time);
    }

    private static String generateRandom(int n) {
        int randomNumber = (int) (Math.random() * n);
        String answer = "" + randomNumber;
        if (answer.length() > 3) {
            answer = answer.substring(0, 4);
        }
        return answer;
    }

    class TradeEventAction {
        private IMessage.Type messageType;
        private String nextBlockId = "";
        private String positionLabel = "";
        private int flowId = 0;

        public IMessage.Type getMessageType() {
            return messageType;
        }

        public void setMessageType(IMessage.Type messageType) {
            this.messageType = messageType;
        }

        public String getNextBlockId() {
            return nextBlockId;
        }

        public void setNextBlockId(String nextBlockId) {
            this.nextBlockId = nextBlockId;
        }
        public String getPositionLabel() {
            return positionLabel;
       }

        public void setPositionLabel(String positionLabel) {
            this.positionLabel = positionLabel;
        }
        public int getFlowId() {
            return flowId;
        }
        public void setFlowId(int flowId) {
            this.flowId = flowId;
        }
    }
}


Attachments:
123122.java [11.36 KiB]
Downloaded 132 times
DISCLAIMER: Dukascopy Bank SA's waiver of responsability - Documents, data or information available on this webpage may be posted by third parties without Dukascopy Bank SA being obliged to make any control on their content. Anyone accessing this webpage and downloading or otherwise making use of any document, data or information found on this webpage shall do it on his/her own risks without any recourse against Dukascopy Bank SA in relation thereto or for any consequences arising to him/her or any third party from the use and/or reliance on any document, data or information found on this webpage.
 

Jump to:  

  © 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