KLineChart 함수를 사용하여 전략 그리기 디자인을 더 쉽게

저자:작은 꿈, 창작: 2022-07-05 15:13:55, 업데이트: 2023-09-25 19:49:32

img

KLineChart 함수를 사용하여 전략 그리기 디자인을 더 쉽게

전략을 설계할 때, 표시하기 위해 전략 차트를 설계하는 것이 종종 필요합니다. 자바스크립트 언어, 파이썬 언어로 전략을 작성할 때, 프로그래밍이나 FMZ 플랫폼에서 사용되는 차트 라이브러리를 잘 모르는 사용자는 종종 사용자 지정 차트에 그림을 그리기 위해 코드 디자인에 어려움을 겪습니다.

이 간단하고 강력한 방식의 그림은 풍부한 그림 기능으로 유명한 파이어 언어에서 볼 수 있습니다. 파이어 언어의 그림 인터페이스를 자바스크립트 및 파이썬 언어의 전략과 연결할 수 있다면 개발자의 디자인 전략의 그림 기능을 크게 용이하게 할 것입니다. 따라서 FMZ 플랫폼은 이러한 수요를 기반으로 사용자 지정 그림 기능을 업그레이드하고 웹을 사용하는 방법을 확장했습니다.KLineChart사용자 정의 차트를 그리는 기능입니다. API 문서를 참조할 수 있습니다:https://www.fmz.com/api#klinechart

자바스크립트 언어를 사용하여 간단한 예를 작성하여 전환을 시작합시다.

간단한 예제

/*backtest
start: 2022-03-21 09:00:00
end: 2022-06-21 15:00:00
period: 30m
basePeriod: 15m
exchanges: [{"eid":"Binance","currency":"BTC_USDT"}]
*/

function main() {
    var c = KLineChart()
    while (true) {
        var bars = _C(exchange.GetRecords)
        for (var i = 0 ; i < bars.length ; i++) {
            var bar = bars[i]
            c.begin(bar)
            c.plot(bar.Volume, "Close")
            c.close()
        }
        Sleep(1000)
    }
}

이 예는 매우 간단합니다. 전략의 사용자 지정 그림 영역에 K-라인 차트를 그리고 차트의 하위 차트 위치에 있는 각 K-라인 BAR에 대응하는 볼륨 곡선을 그리는 것입니다.

img

코드에서 우리는var c = KLineChart()먼저 그래프 객체를 만들고 그 다음 그 방법을 사용하여 그래프를 그리는 것입니다. 그 다음 루프에서 우리는 K-라인 데이터 (열 구조) 를 얻고 K-라인 배열을 가로질러 갈 수 있습니다. 예를 들어 간단한 for 루프를 사용하여 가로질러 갈 수 있습니다. 또는 다른 방법으로 가로질러 갈 수 있습니다.

도영 작업은c.begin(bar)기능과 끝c.close()기능.begin그리고close함수는 차트 객체의 모든 방법입니다. 다음으로, 가장 일반적으로 사용되는 그림 함수를 사용plot각 BAR에 부피 곡선을 그리기 위해서

더 복잡한 예

볼링거 지표가 붙어 있는 차트를 디자인하고 싶다고 가정해 봅시다. 그리고 각 BAR의 볼륨 차트도 있습니다.

/*backtest
start: 2022-03-21 09:00:00
end: 2022-06-21 15:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"BTC_USDT"}]
*/

function main() {
    var c = KLineChart()

    // main strategy loop
    while(true) {
        // polling interval
        Sleep(500)
        
        // get K-line data
        let bars = exchange.GetRecords()
        if (!bars || bars.length <= 20) {
            continue
        }
        
        // calculate the Bollinger indicator
        var boll = TA.BOLL(bars)
        
        bars.forEach(function(bar, index) {
            c.begin(bar)
            // drawing operation
            c.plot(boll[0][index], "Boll_Up", {overlay: true})     // Draw on the main chart
            c.plot(boll[1][index], "Boll_Mid", {overlay: true})    // Draw on the main chart
            c.plot(boll[2][index], "Boll_Down", {overlay: true})   // Draw on the main chart
            c.plot(bar.Volume, "volume")                           // Draw on the sub-chart
            c.close()
        })
    
        // Strategy trading logic
        // ...
        // ..
    }
}

코드에서 볼 수 있듯이 FMZ 플랫폼의 백테스트 구성 정보는

/*backtest
start: 2022-03-21 09:00:00
end: 2022-06-21 15:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"BTC_USDT"}]
*/

이러한 구성은 Binance 스팟 거래소 객체 백테스팅 테스트를 사용하는 것입니다. 백테스팅 효과는 다음과 같습니다.

img

우리는 파인 (Pine) 의 그림 방법을 사용한다는 것을 알 수 있습니다. 이것은 자바스크립트 언어의 그림 코드를 크게 단순화합니다.

차트를 그리기 위해 지표와 다른 데이터를 입력

K-라인 데이터를 얻고 지표를 계산하는 작업은 플랫폼 전략 광장 및 API 문서의 전략 예제에서 일반적이고 간단합니다.

        // obtain K-line data
        let bars = exchange.GetRecords()
        if (!bars || bars.length <= 20) {   
            // If the acquisition of the K line fails, that is, if !bar is true, execute continue, ignore the following code, and re-execute the loop
            // If bars.length is less than or equal to 20, that is, the number of K-line BAR (bar) is less than 20, the indicator cannot be calculated, and continue is also executed
            continue
        }
        
        // Calculate the Bollinger indicator
        var boll = TA.BOLL(bars)

볼링거 지표 계산 함수 TA.BOLL, 볼링거 지표 매개 변수가 지정되지 않은 경우 기본 매개 변수BOLL(20, 2)볼링거 지표는 세 줄이 있으므로 TA.BOLL 함수가 반환하는 데이터는 2 차원 배열입니다. boll[0], boll[1], boll[2]는 각 선을 나타내는 배열의 세 요소입니다.

  • boll[0]: 볼링거 밴드
  • boll[1]: 볼링거 밴드 중간선
  • boll[2]: 볼링거 밴드 하향선

그러면 K선 데이터의 부피, 즉 부피와 계산된 볼링거 지표 데이터를 차트에 어떻게 그리는지 볼 것입니다.

우리는 K-라인 데이터를 바에 바를 그려서 K-라인 배열 전체를 통과해야 합니다.forEach이 방법은 트러스 (traverse) 를 위해 사용되거나 for 루프는 트러스 (traverse) 를 위해 사용될 수 있습니다.

        bars.forEach(function(bar, index) {
            c.begin(bar)
            // Drawing operations
            c.plot(boll[0][index], "Boll_Up", {overlay: true})     // {overlay: true} Parameter control, drawn on the main chart
            c.plot(boll[1][index], "Boll_Mid", {overlay: true})    // Draw on the main chart
            c.plot(boll[2][index], "Boll_Down", {overlay: true})   // Draw on the main chart
            c.plot(bar.Volume, "volume")                           // Draw on the sub-chart
            c.close()
        })

표시를 시작 할 때마다 표시를 해야 합니다.c.begin(bar)함수 호출 먼저.begin이 함수는 우리의 그래프 객체 c 방법 중 하나입니다.c.close()전화해야 합니다.begin기능 및closefunction는 우리가 Pine 언어의 그림 방법과 비슷한 것을 부르는 그림 함수입니다.barcolor bgcolor plot fill hline plotarrow plotshape plotchar plotcandle signal, 당신은 선, 화살표, 표시 정보 등을 그릴 수 있습니다. 이러한 함수의 매개 변수는 파이어 언어에 대응하는 함수 매개 변수와 동일하며, 그리고 그릴 함수 또한 동일합니다.

거래 신호 화살표, 마커, 수평선 등을 그리는 것을 추가합니다.

위의 볼링거 밴드 차트 예제에는 거래 신호 화살표, 마커, 수평 선을 추가하십시오.

/*backtest
start: 2022-03-21 09:00:00
end: 2022-06-21 15:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"BTC_USDT"}]
*/

function main() {
    var c = KLineChart({overlay : true})

    // Strategy main loop
    while(true) {
        // Polling interval
        Sleep(500)
        
        // Obtain K-line data
        let bars = exchange.GetRecords()
        if (!bars || bars.length <= 20) {
            continue
        }
        
        // Calculate Bollinger indicator
        var boll = TA.BOLL(bars)
        
        bars.forEach(function(bar, index) {
            c.begin(bar)
            // Drawing operations
            c.plot(boll[0][index], "Boll_Up", {overlay: true})     // Draw on the main chart
            c.plot(boll[1][index], "Boll_Mid", {overlay: true})    // Draw on the main chart
            c.plot(boll[2][index], "Boll_Down", {overlay: true})   // Draw on the main chart
            c.plot(bar.Volume, "volume", {overlay: false})         // Draw on the sub-chart
            
            c.hline(bar.Open, {overlay: true})                          // Horizontal line
            c.plotarrow(bar.Close - bar.Open, {overlay: true})          // Arrow
            c.plotshape(bar.Close - bar.Open > 0, {style: 'square'})    // Draw square markers
            c.plotchar(bar.Close - bar.Open < 0, {char: 'X'})           // Draw the character X
            
            c.close()
        })
    
        // Strategy trading logic
        // ...
        // ..
    }
}

img

차트 구성 객체

그래프 스타일을 구성하기 위해 구조를 선언할 수 있습니다. 예를 들어, 다음 차트Cfg 변수는 그리드 라인의 구성 정보를 나타냅니다.

    var chartCfg = {
        grid: {
            show: true,
            // Grid horizontal line
            horizontal: {
                show: true,
                size: 2,
                color: '#FF0000',    // Color of horizontal grid line
                // 'solid'|'dash'
                style: 'dash',       // Type of line
                dashValue: [2, 2]
            },
   	        // Grid vertical line
            vertical: {
                show: true,
                size: 2,
                color: '#32CD32',
                // 'solid'|'dash'
                style: 'solid',
                dashValue: [2, 2]
            }
        },
    }

차트 구성 객체는 차트의 일부 속성과 외형을 설정하는 데이터 구조입니다. 예를 들어, 그리드 라인 스타일 구성은 예제에서 사용됩니다. X축, Y축 관련 설정, 커서 라인 설정, 경고 메시지 설정, 기술 지표 스타일 설정, K-라인 BAR 스타일 설정 등으로 구성 및 수정 할 수있는 많은 옵션도 있습니다.

물론, 만약 당신이 이러한 익숙하지 않은 경우, 당신은 차트 구성 객체에서 전달 할 수 없습니다 호출 할 때KLineChart그래프 객체를 생성하는 함수. 그러면 생성된 차트는 기본 스타일입니다. API 함수를 사용KLineChartFMZ 플랫폼의 기능으로 차트 객체를 생성합니다.

var c = KLineChart(chartCfg)

그리드 라인을 그리기 위한 시험 코드:

/*backtest
start: 2022-03-21 09:00:00
end: 2022-06-21 15:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Binance","currency":"BTC_USDT"}]
*/

function main() {
    var chartCfg = {
        grid: {
            show: true,
            // Grid horizontal line
            horizontal: {
                show: true,
                size: 2,
                color: '#FF0000',
                // 'solid'|'dash'
                style: 'dash',
                dashValue: [2, 2]
            },
   	        // Grid vertical line
            vertical: {
                show: true,
                size: 2,
                color: '#32CD32',
                // 'solid'|'dash'
                style: 'solid',
                dashValue: [2, 2]
            }
        },
    }

    var c = KLineChart(chartCfg)

    // Strategy main loop
    while(true) {
        // Polling interval
        Sleep(500)
        
        // Obtain K-line data
        var bars = _C(exchange.GetRecords)
        bars.forEach(function(bar, index) {
            c.begin(bar)
            c.close()
        })
    
        // Strategy trading logic
        // ...
        // ..
    }
}

img

그래프 구성 스타일의 예

차트 구성 스타일 설정을 참조하는 데 사용할 수 있습니다.

{
    // Gridlines
    grid: {
        show: true,
        // Grid horizontal line
        horizontal: {
            show: true,
            size: 1,
            color: '#393939',
            // 'solid'|'dash'
            style: 'dash',
            dashValue: [2, 2]
        },
        // Grid vertical line
        vertical: {
            show: false,
            size: 1,
            color: '#393939',
            // 'solid'|'dash'
            style: 'dash',
            dashValue: [2, 2]
        }
    },
    // Candlestick chart
    candle: {
        // The distance between the top and bottom of the candlestick chart, greater than 1 is the absolute value, greater than 0, and 1 is the proportion
        margin: {
            top: 0.2,
            bottom: 0.1
        },
        // Type of Candlestick Charts 'candle_solid'|'candle_stroke'|'candle_up_stroke'|'candle_down_stroke'|'ohlc'|'area'
        type: 'candle_solid',
        // Candle pillar
        bar: {
            upColor: '#26A69A',
            downColor: '#EF5350',
            noChangeColor: '#888888'
        },
        // Area map
        area: {
            lineSize: 2,
            lineColor: '#2196F3',
            value: 'close',
            backgroundColor: [{
                offset: 0,
                color: 'rgba(33, 150, 243, 0.01)'
            }, {
                offset: 1,
                color: 'rgba(33, 150, 243, 0.2)'
            }]
        },
        priceMark: {
            show: true,
            // Highest price marker
            high: {
                show: true,
                color: '#D9D9D9',
                textMargin: 5,
                textSize: 10,
                textFamily: 'Helvetica Neue',
                textWeight: 'normal'
            },
            // Lowest price marker
            low: {
                show: true,
                color: '#D9D9D9',
                textMargin: 5,
                textSize: 10,
                textFamily: 'Helvetica Neue',
                textWeight: 'normal',
            },
            // Latest price marker
            last: {
                show: true,
                upColor: '#26A69A',
                downColor: '#EF5350',
                noChangeColor: '#888888',
                line: {
                    show: true,
                    // 'solid'|'dash'
                    style: 'dash',
                    dashValue: [4, 4],
                    size: 1
                },
                text: {
                    show: true,
                    size: 12,
                    paddingLeft: 2,
                    paddingTop: 2,
                    paddingRight: 2,
                    paddingBottom: 2,
                    color: '#FFFFFF',
                    family: 'Helvetica Neue',
                    weight: 'normal',
                    borderRadius: 2
                }
            }
        },
        // Tips
        tooltip: {
            // 'always' | 'follow_cross' | 'none'
            showRule: 'always',
            // 'standard' | 'rect'
            showType: 'standard',
            labels: ['time', 'open', 'close', 'high', 'low', 'volume'],
            values: null,
            defaultValue: 'n/a',
            rect: {
                paddingLeft: 0,
                paddingRight: 0,
                paddingTop: 0,
                paddingBottom: 6,
                offsetLeft: 8,
                offsetTop: 8,
                offsetRight: 8,
                borderRadius: 4,
                borderSize: 1,
                borderColor: '#3f4254',
                backgroundColor: 'rgba(17, 17, 17, .3)'
            },
            text: {
                size: 12,
                family: 'Helvetica Neue',
                weight: 'normal',
                color: '#D9D9D9',
                marginLeft: 8,
                marginTop: 6,
                marginRight: 8,
                marginBottom: 0
            }
        }
    },
    // Technical indicators
    technicalIndicator: {
        margin: {
            top: 0.2,
            bottom: 0.1
        },
        bar: {
            upColor: '#26A69A',
            downColor: '#EF5350',
            noChangeColor: '#888888'
        },
        line: {
            size: 1,
            colors: ['#FF9600', '#9D65C9', '#2196F3', '#E11D74', '#01C5C4']
        },
        circle: {
            upColor: '#26A69A',
            downColor: '#EF5350',
            noChangeColor: '#888888'
        },
        // Latest value marker
        lastValueMark: {
            show: false,
            text: {
                show: false,
                color: '#ffffff',
                size: 12,
                family: 'Helvetica Neue',
                weight: 'normal',
                paddingLeft: 3,
                paddingTop: 2,
                paddingRight: 3,
                paddingBottom: 2,
                borderRadius: 2
            }
        },
        // Tips
        tooltip: {
            // 'always' | 'follow_cross' | 'none'
            showRule: 'always',
            // 'standard' | 'rect'
            showType: 'standard',
            showName: true,
            showParams: true,
            defaultValue: 'n/a',
            text: {
                size: 12,
                family: 'Helvetica Neue',
                weight: 'normal',
                color: '#D9D9D9',
                marginTop: 6,
                marginRight: 8,
                marginBottom: 0,
                marginLeft: 8
            }
        }
    },
    // x-axis
    xAxis: {
        show: true,
        height: null,
        // x-axis line
        axisLine: {
            show: true,
            color: '#888888',
            size: 1
        },
        // x-axis split text
        tickText: {
            show: true,
            color: '#D9D9D9',
            family: 'Helvetica Neue',
            weight: 'normal',
            size: 12,
            paddingTop: 3,
            paddingBottom: 6
        },
        // x-axis split line
        tickLine: {
            show: true,
            size: 1,
            length: 3,
            color: '#888888'
        }
    },
    // y-axis
    yAxis: {
        show: true,
        width: null,
        // 'left' | 'right'
        position: 'right',
        // 'normal' | 'percentage' | 'log'
        type: 'normal',
        inside: false,
        reverse: false,
        // y-axis line
        axisLine: {
            show: true,
            color: '#888888',
            size: 1
        },
        // y-axis split text
        tickText: {
            show: true,
            color: '#D9D9D9',
            family: 'Helvetica Neue',
            weight: 'normal',
            size: 12,
            paddingLeft: 3,
            paddingRight: 6
        },
        // y-axis split line
        tickLine: {
            show: true,
            size: 1,
            length: 3,
            color: '#888888'
        }
    },
    // Split line between charts
    separator: {
        size: 1,
        color: '#888888',
        fill: true,
        activeBackgroundColor: 'rgba(230, 230, 230, .15)'
    },
    // Crosshair
    crosshair: {
        show: true,
        // Horizontal line and text of crosshair
        horizontal: {
            show: true,
            line: {
                show: true,
                // 'solid'|'dash'
                style: 'dash',
                dashValue: [4, 2],
                size: 1,
                color: '#888888'
            },
            text: {
                show: true,
                color: '#D9D9D9',
                size: 12,
                family: 'Helvetica Neue',
                weight: 'normal',
                paddingLeft: 2,
                paddingRight: 2,
                paddingTop: 2,
                paddingBottom: 2,
                borderSize: 1,
                borderColor: '#505050',
                borderRadius: 2,
                backgroundColor: '#505050'
            }
        },
        // Vertical line and text of crosshair
        vertical: {
            show: true,
            line: {
                show: true,
                // 'solid'|'dash'
                style: 'dash',
                dashValue: [4, 2],
                size: 1,
                color: '#888888'
            },
            text: {
                show: true,
                color: '#D9D9D9',
                size: 12,
                family: 'Helvetica Neue',
                weight: 'normal',
                paddingLeft: 2,
                paddingRight: 2,
                paddingTop: 2,
                paddingBottom: 2,
                borderSize: 1,
                borderColor: '#505050',
                borderRadius: 2,
                backgroundColor: '#505050'
            }
        }
    },
    // Graph
    shape: {
        point: {
            backgroundColor: '#2196F3',
            borderColor: '#2196F3',
            borderSize: 1,
            radius: 4,
            activeBackgroundColor: '#2196F3',
            activeBorderColor: '#2196F3',
            activeBorderSize: 1,
            activeRadius: 6
        },
        line: {
            // 'solid'|'dash'
            style: 'solid'
            color: '#2196F3',
            size: 1,
            dashValue: [2, 2]
        },
        polygon: {
            // 'stroke'|'fill'
            style: 'stroke',
            stroke: {
                // 'solid'|'dash'
                style: 'solid',
                size: 1,
                color: '#2196F3',
                dashValue: [2, 2]
            },
            fill: {
                color: 'rgba(33, 150, 243, 0.1)'
            }
        },
        arc: {
            // 'stroke'|'fill'
            style: 'stroke',
            stroke: {
                // 'solid'|'dash'
                style: 'solid',
                size: 1,
                color: '#2196F3',
                dashValue: [2, 2]
            },
            fill: {
                color: '#2196F3'
            }
        },
        text: {
            style: 'fill',
            color: '#2196F3',
            size: 12,
            family: 'Helvetica Neue',
            weight: 'normal',
            offset: [0, 0]
        }
    },
    annotation: {
        // 'top' | 'bottom' | 'point'
        position: 'top',
        offset: [20, 0]
        symbol: {
            // 'diamond' | 'circle' | 'rect' | 'triangle' | 'custom' | 'none'
            type: 'diamond',
            size: 8,
            color: '#2196F3',
            activeSize: 10,
            activeColor: '#FF9600'
        }
    },
    tag: {
        // 'top' | 'bottom' | 'point'
        position: 'point',
        offset: 0,
        line: {
            show: true,
            style: LineStyle.DASH,
            dashValue: [4, 2],
            size: 1,
            color: '#2196F3'
        },
        text: {
            color: '#FFFFFF',
            backgroundColor: '#2196F3',
            size: 12,
            family: 'Helvetica Neue',
            weight: 'normal',
            paddingLeft: 2,
            paddingRight: 2,
            paddingTop: 2,
            paddingBottom: 2,
            borderRadius: 2,
            borderSize: 1,
            borderColor: '#2196F3'
        },
        mark: {
            offset: 0,
            color: '#FFFFFF',
            backgroundColor: '#2196F3',
            size: 12,
            family: 'Helvetica Neue',
            weight: 'normal',
            paddingLeft: 2,
            paddingRight: 2,
            paddingTop: 2,
            paddingBottom: 2,
            borderRadius: 2,
            borderSize: 1,
            borderColor: '#2196F3'
        }
    }
}

이것이 전략 설계를 더 쉽게 만들지 않습니까?


관련

더 많은