Feeds.java

注意事項:
サンプルソースコードには実際にオーダーを発注するものがあります。
サンプルソースコードのストラテジーを起動する場合は、必ずデモ口座で行ってください。



// Copyright (c) 2009 Dukascopy (Suisse) SA. All Rights Reserved.

package feed;

import com.dukascopy.api.*;
import java.util.HashSet;
import java.util.Set;
import com.dukascopy.api.drawings.IChartObjectFactory;
import com.dukascopy.api.drawings.IOhlcChartObject;
import com.dukascopy.api.indicators.OutputParameterInfo.DrawingStyle;
import java.awt.Color;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Map;
import com.dukascopy.api.drawings.IChartDependentChartObject;
import com.dukascopy.api.drawings.ITriangleChartObject;
import com.dukascopy.api.drawings.ITextChartObject;

//1. インポート追加
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.feed.IFeedDescriptor;
import com.dukascopy.api.feed.IFeedListener;
import com.dukascopy.api.feed.util.RenkoFeedDescriptor;
import com.dukascopy.api.feed.util.TimePeriodAggregationFeedDescriptor;

//2. IFeedListenerインターフェースの実装
public class Feeds implements IStrategy, IFeedListener {

    private IEngine        engine;
    private IConsole       console;
    private IHistory       history;
    private IContext       context;
    private IIndicators    indicators;
    private IUserInterface userInterface;
    private IBar           previousBar;
    private IOrder         order;
    private IChart              openedChart;
    private IChartObjectFactory factory;
    private int                 signals;
    private static final int PREV = 1;
    private static final int SECOND_TO_LAST = 0;
    private int     uniqueOrderCounter   = 1;
    private SMATrend previousSMADirection = SMATrend.NOT_SET;
    private SMATrend currentSMADirection  = SMATrend.NOT_SET;
    private Map<IOrder, Boolean> createdOrderMap = new HashMap<IOrder, Boolean>();
    private int shorLineCounter;
    private int textCounterOldSL;
    private int textCounterNewSL;

    @Configurable("チャート上にOHLCインデックス表示")
    public boolean addOHLC = true;
    @Configurable("フィルター")
    public Filter filter = Filter.WEEKENDS;
    @Configurable("SMA描画")
    public boolean drawSMA = true;
    @Configurable("ストラテジー停止時にチャートを閉じる")
    public boolean closeChart;
    @Configurable("ストップロス(pips)")
    public int    stopLossPips   = 10;
    @Configurable("リミット(pips)")
    public int    takeProfitPips = 10;
    @Configurable("ブレークイーブン(pips)")
    public double breakEventPips = 5;
    @Configurable( "SMA期間" )
    public int smaTimePeriod = 30;


    // 3. パラメータの削除 

    //@Configurable(value = "Instrument value")
    //public Instrument myInstrument = Instrument.EURGBP;
    //@Configurable(value = "Offer Side value", obligatory = true)
    //public OfferSide myOfferSide;
    //@Configurable(value = "Period value")
    //public Period myPeriod = Period.TEN_MINS;



    // 4. パラメータ追加。ストラテジー起動時にフィードタイプを選択する事が出来ます。
    @Configurable("フィードタイプ")
    public FeedType myFeed = FeedType.RENKO_2_PIPS_EURGBP_BID;

    private enum SMATrend {
        UP, DOWN, NOT_SET;
    }

    // 5. 新しい列挙型を定義

    public enum FeedType {
    
        // 列挙の定義
        RENKO_2_PIPS_EURGBP_BID (  new RenkoFeedDescriptor(Instrument.EURGBP, PriceRange.TWO_PIPS, OfferSide.BID)),
        TIME_BAR_30_SEC_EURGBP_BID (new TimePeriodAggregationFeedDescriptor(Instrument.EURGBP, Period.THIRTY_SECS,
                                    OfferSide.BID, Filter.WEEKENDS));
    
        // フィールド変数
        private final IFeedDescriptor feedDescriptor;
    
        // コンストラクタ
        FeedType(IFeedDescriptor feedDescriptor) {
            this.feedDescriptor = feedDescriptor;
        }
    
        // Getメソッド
        public IFeedDescriptor getFeedDescriptor(){
            return feedDescriptor;
        }      
    }

    // 6. onStartメソッドでフィード登録を行う
    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();
        this.openedChart = context.getChart(myFeed.getFeedDescriptor().getInstrument());
        this.factory     = openedChart.getChartObjectFactory();

        Set<Instrument> instruments = new HashSet<Instrument>();
        instruments.add(myFeed.getFeedDescriptor().getInstrument());
        context.setSubscribedInstruments(instruments, true);

        if( drawSMA ) {
            if( !addToChart(openedChart) ){
                printMeError("チャート上にインジケータをプロット出来ませんでした。チャートの設定値を確認して下さい。");
            }
        }

        // フィード登録
        context.subscribeToFeed(myFeed.getFeedDescriptor(), this);

    } // onStartメソッド終了

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {        
        if( message.getOrder() != null ) {
            console.getOut().println("オーダーラベル: " + message.getOrder().getLabel() 
                                     + " || メッセージログ: " + message.getContent());
        }
    }

    public void onStop() throws JFException {
        if( closeChart )
            context.closeChart(openedChart);
    }

    
    public void onTick(Instrument instrument, ITick tick) throws JFException {
        // 拡張forループ
        for ( Map.Entry<IOrder, Boolean> entry : createdOrderMap.entrySet() ) {
            IOrder   currentOrder = entry.getKey();
            boolean currentValue = entry.getValue();
    
            if ( currentValue == false && currentOrder.getProfitLossInPips() >= breakEventPips ) {
                printMe( currentOrder.getProfitLossInPips() + "pipsリミットのポジションのストップロスは"
                           + "エントリーレートに移動しました。");
                addBreakToChart( currentOrder, tick, currentOrder.getStopLossPrice(), currentOrder.getOpenPrice() );
    
                // ストップロス変更を表示するラインをチャートに追加
                currentOrder.setStopLossPrice( currentOrder.getOpenPrice() );
                entry.setValue( true );
            }
        }
    }// onTickメソッド終了

    
    @Override
    public void onFeedData(IFeedDescriptor feedDescriptor, ITimedData feedData) {

        Instrument myInstrument = feedDescriptor.getInstrument();
        OfferSide myOfferSide = feedDescriptor.getOfferSide();

        try {
            if ( !(feedData instanceof IBar) ) {
                printMeError("ティックフィードデータは使えません。");
                return;
            }

            IBar bar = (IBar) feedData;

            int  candlesBefore = 2, candlesAfter = 0;
            long completedBarTimeL = bar.getTime();

            Object[] smaObjectsFeed = indicators.calculateIndicator(feedDescriptor, new OfferSide[]{myOfferSide}, "SMA",
                                         new AppliedPrice[]{AppliedPrice.CLOSE}, new Object[]{smaTimePeriod}, candlesBefore, 
                                         feedData.getTime(), candlesAfter);
            double[] sma = (double[]) smaObjectsFeed[0]; // sma has just 1 output            


            IEngine.OrderCommand myCommand = null;
            printMe(String.format("SMAの値: 2つ前 = %.5f; 1つ前 = %.5f", sma[SECOND_TO_LAST], sma[PREV]));

            if( sma[PREV] > sma[SECOND_TO_LAST]){
                printMe("SMA上昇"); // インジケータが上昇している
                myCommand = IEngine.OrderCommand.BUY;
                currentSMADirection = SMATrend.UP;
            } else if ( sma[PREV] < sma[SECOND_TO_LAST]){
                printMe("SMA下降"); // インジケータが下降している
                myCommand = IEngine.OrderCommand.SELL;
                currentSMADirection = SMATrend.DOWN;
            } else {
                return;
            }
    
            double lastTickBid           = history.getLastTick(myInstrument).getBid();
            double lastTickAsk           = history.getLastTick(myInstrument).getAsk();
            double stopLossValueForLong  = myInstrument.getPipValue() * stopLossPips;
            double stopLossValueForShort = myInstrument.getPipValue() * takeProfitPips;
            double stopLossPrice   = myCommand.isLong() ? (lastTickBid - stopLossValueForLong ) : (lastTickAsk + stopLossValueForLong);
            double takeProfitPrice = myCommand.isLong() ? (lastTickBid + stopLossValueForShort) : (lastTickAsk - stopLossValueForShort);
    
            // SMAトレンドが変わったら、新しいオーダーを行う
            if ( currentSMADirection != previousSMADirection ) {
                previousSMADirection = currentSMADirection;
                    IOrder newOrder = engine.submitOrder("MyStrategyOrder" + uniqueOrderCounter++, myInstrument, myCommand, 
                                                           0.001, 0, 1, stopLossPrice, takeProfitPrice);
                createdOrderMap.put(newOrder, false);
    
                if( openedChart == null ){
                    return;
                }

                // IFeedDescriptorオブジェクトから現在の時間軸を取得
                long   time  = history.getFeedData(feedDescriptor, 0).getTime(); // 現在のバーにISignalDownChartObjectを描画する為の時間
                double space = myInstrument.getPipValue() * 2; // ISignalDownChartObjectの為に、バーの上または下にマージンを設ける
                IChartDependentChartObject signal = myCommand.isLong()
                        ? factory.createSignalUp(  "signalUpKey"   + signals++, time, bar.getLow()  - space)
                        : factory.createSignalDown("signalDownKey" + signals++, time, bar.getHigh() + space);

                signal.setText("MyStrategyOrder" + (uniqueOrderCounter - 1));
                openedChart.addToMainChart(signal);
            }
        } catch (Exception e) {

        }

    }

     // 9. onBarメソッドの全ロジックをonFeedDataメソッドへ移動
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {            
    }

    private void printMe(Object toPrint){
        console.getOut().println(toPrint);
    }
    

    private void printMeError(Object o){
        console.getErr().println(o);
    }

    private boolean addToChart(IChart chart){
        if ( !checkChart(chart) ) {
            return false;
        }

        chart.addIndicator(indicators.getIndicator("SMA"), new Object[] {smaTimePeriod},
                new Color[]{Color.BLUE}, new DrawingStyle[]{DrawingStyle.LINE}, new int[]{3});

        if(addOHLC){
    
            IOhlcChartObject ohlc = null;
            for (IChartObject obj : chart.getAll()) {
                if (obj instanceof IOhlcChartObject) {
                    ohlc = (IOhlcChartObject) obj;
                }
            }
    
            if (ohlc == null) {
                ohlc = chart.getChartObjectFactory().createOhlcInformer();
                ohlc.setPreferredSize(new Dimension(100, 200));
                chart.addToMainChart(ohlc);
            }
    
            // OHLCインデックスを表示
            ohlc.setShowIndicatorInfo(true);
        }
        return true;
    }// addToChartメソッドの終了

    
    private void addBreakToChart(IOrder changedOrder, ITick tick, double oldSL, double newSL) throws JFException {
        if ( openedChart == null ) {
            return;
        }
    
        ITriangleChartObject orderSLTriangle = factory.createTriangle("Triangle " + shorLineCounter++,
                changedOrder.getFillTime(), changedOrder.getOpenPrice(), tick.getTime(), oldSL, tick.getTime(), newSL);
    
        Color lineColor = oldSL > newSL ? Color.RED : Color.GREEN;
        orderSLTriangle.setColor(lineColor);
        orderSLTriangle.setLineStyle(LineStyle.SOLID);
        orderSLTriangle.setLineWidth(1);
        orderSLTriangle.setStickToCandleTimeEnabled(false);
        openedChart.addToMainChart(orderSLTriangle);
    
        // テキスト描画
        String breakTextOldSL       = String.format(" Old SL: %.5f", oldSL);
        String breakTextNewSL       = String.format(" New SL: %.5f", newSL);
        double pipValue = myFeed.getFeedDescriptor().getInstrument().getPipValue();
        double textVerticalPosition = oldSL > newSL ? newSL - pipValue : newSL + pipValue;
        ITextChartObject textOldSL   = factory.createText("textKey1" + textCounterOldSL++, tick.getTime(), oldSL);
        ITextChartObject textNewSL   = factory.createText("textKey2" + textCounterNewSL++, tick.getTime(), newSL);

        textOldSL.setText(breakTextOldSL);
        textNewSL.setText(breakTextNewSL);
        textOldSL.setStickToCandleTimeEnabled(false);
        textNewSL.setStickToCandleTimeEnabled(false);
        openedChart.addToMainChart(textOldSL);
        openedChart.addToMainChart(textNewSL);
    }
    

    private boolean checkChart(IChart chart) {
        if (chart == null ) {
            printMeError( myFeed.getFeedDescriptor().getInstrument() + " のチャートが開かれていません。" );
            return false;
        }
        if (chart.getSelectedOfferSide() != myFeed.getFeedDescriptor().getOfferSide()) {
            printMeError( myFeed.getFeedDescriptor().getOfferSide() + "のオーダータイプのチャートが開かれていません。" );
            return false;
        }

        if (chart.getFeedDescriptor().getDataType() == DataType.RENKO) {
            if (chart.getPriceRange() != myFeed.getFeedDescriptor().getPriceRange()) {
                printMeError(myFeed.getFeedDescriptor().getPriceRange() + "の価格期間のチャートが開かれていません。" );
                return false;
            }
        } else if (chart.getFeedDescriptor().getDataType() == DataType.TIME_PERIOD_AGGREGATION) {
            if (chart.getSelectedPeriod() != myFeed.getFeedDescriptor().getPeriod()) {
                printMeError( myFeed.getFeedDescriptor().getPeriod() + "の時間軸のチャートが開かれていません。" );
                return false;
            }
        }

        if (chart.getFilter() != this.filter) {
            printMeError( this.filter + "のチャートフィルターではありません " );
            return false;
        }
        return true;
    }
}








スポンサーリンク

スポンサーリンク
検索
リファレンスツリー


Copyright ©2016 JForexAPIで自動売買させ隊! All Rights Reserved.


Top

inserted by FC2 system