更新日:2024/1/23

JSTraderカスタムストラテジー


export default [
    (): Strategy<
        {
            fast: { period: number; lineColor: string };
            slow: { period: number; lineColor: string };
        },
        {
            fastSMA: Indicator;
            slowSMA: Indicator;
            buyPositionCount: number;
            sellPositionCount: number;
        },
        {}
    > => ({
        type: "s",
        name: "sample.smaCrossStrategy",
        onInit() {
            this.shortName = "smaCross";
            const params = this.params;
            const origParams = IndicatorUtil.getParameter("sample.SMA");
            const fastParams = { ...origParams, ...params.fast };
            const slowParams = { ...origParams, ...params.slow };
            this.fastSMA = this.chart.mainContainerIndicator.addItemIndicator!(
                "sample.SMA",
                fastParams,
            );
            this.slowSMA = this.chart.mainContainerIndicator.addItemIndicator!(
                "sample.SMA",
                slowParams,
            );
            this.buyPositionCount = 0;
            this.sellPositionCount = 0;
        },
        onChartChange({
            index,
            isBarChanged,
        }) {
            const fastBuffer = (this.fastSMA as any).smaBuffer;
            const slowBuffer = (this.slowSMA as any).smaBuffer;
            if (isBarChanged) {
                if (
                    fastBuffer.get(index - 2) <= slowBuffer.get(index - 2) &&
                    fastBuffer.get(index - 1) > slowBuffer.get(index - 1)
                ) {
                    if (this.sellPositionCount > 0) {
                        this.entry({ orderType: "market", direction: "buy", lot: 1 });
                        this.sellPositionCount = 0;
                    }
                    if (this.buyPositionCount === 0) {
                        this.entry({ orderType: "market", direction: "buy", lot: 1 });
                        this.buyPositionCount = 1;
                    }
                }
                if (
                    fastBuffer.get(index - 2) >= slowBuffer.get(index - 2) &&
                    fastBuffer.get(index - 1) < slowBuffer.get(index - 1)
                ) {
                    if (this.buyPositionCount > 0) {
                        this.entry({ orderType: "market", direction: "sell", lot: 1 });
                        this.buyPositionCount = 0;
                    }
                    if (this.sellPositionCount === 0) {
                        this.entry({ orderType: "market", direction: "sell", lot: 1 });
                        this.sellPositionCount = 1;
                    }
                }
            }
        },
        params: {
            fast: {
                period: 10,
                lineColor: "lime",
            },
            slow: {
                period: 30,
                lineColor: "cyan",
            },
        },
    }),
];