크로코다일 라인 거래 시스템 파이썬 버전

저자:선함, 2020-05-07 14:33:19, 업데이트: 2023-11-06 19:40:42

img

요약

금융 거래를 한 사람들은 아마도 경험을 할 것입니다. 때로는 가격 변동이 규칙적이지만 더 자주 무작위 행진의 불안정한 상태를 보여줍니다. 시장 위험과 기회가있는 곳이 바로 이러한 불안정성입니다. 불안정성은 예측 불가능하다는 것을 의미합니다. 따라서 예측 불가능한 시장 환경에서 수익을 더 안정적으로 만드는 방법 또한 모든 거래자에게 문제가됩니다. 이 기사는 모든 사람들에게 영감을 줄 것으로 기대하여 악어 거래 규칙 전략을 소개합니다.

독수리 선이란 무엇인가요?

img

악어선은 실제로 파란색 선의 턱, 빨간 선의 치아, 녹색 선의 상턱과 일치하는 세 가지 특별한 이동 평균이다. 턱은 13 기간 이동 평균이며 미래에 8 바를 이동한다. 이빨은 8 기간 이동 평균이며 미래에 5 바를 이동한다. 상唇은 5 기간 이동 평균이며 미래에 3 바를 이동한다.

악어 선의 원칙

악어 선은 기하학과 비선형 역학에 기초하여 요약된 기술 분석 방법의 집합이다. 악어의 턱, 치아 및 상쪽 입술이 닫히거나 얽매일 때 악어가 잠든다는 것을 의미합니다. 이 시점에서 우리는 일반적으로 파편이 나타나기 전까지 시장 밖에서 머물며 명백한 트렌드 시장에만 참여합니다.

악어가 잠을 더 오래 자는수록 깨어나면 더 배고프기 때문에 깨어나면 입술을 크게 펴게 된다. 상唇이 이빨 위에 있고 이빨이 턱 위에 있다면 시장이 황소 시장에 진입하고 악어가 쇠고기를 먹을 것이라는 것을 나타낸다. 상唇이 이빨 아래와 이빨이 턱 아래라면 시장이 곰 시장에 진입하고 악어가 곰 고기를 먹을 것이라는 것을 나타낸다. 턱이 꽉 차기 전까지는 다시 입을 닫을 것이다.

크로코다일 선 계산 공식

위 입술 = REF ((SMA ((VAR1,5,1),3) 치아 = REF ((SMA ((VAR1,8,1),5) = REF ((SMA ((VAR1,13,1)

악어 전략 구성

단계 1: 전략 프레임워크를 작성

# Strategy main function
def onTick():
     pass

# Program entry
def main ():
     while True: # Enter infinite loop mode
         onTick() # execute strategy main function
         Sleep(1000) # sleep for 1 second

FMZ 투표 모드를 사용하면 하나는 onTick 함수이고 다른 하나는 onTick 함수가 메인 함수에서 무한 루프로 실행되는 메인 함수입니다.

단계 2: 파이썬 라이브러리를 가져오기

import talib
import numpy as np

SMA 함수는 우리의 전략에서 사용됩니다. SMA는 수학적 평균입니다. talib 라이브러리에 이미 준비된 SMA 함수가 있습니다. 그래서 직접 talib 파이썬 라이브러리를 가져오고 직접 호출합니다. 왜냐하면 이 함수를 호출할 때, 당신은 numpy 형식 매개 변수를 전달해야 하기 때문에, 우리는 전략의 시작에서 이 두 파이썬 라이브러리를 가져오기 위해 수입을 사용해야합니다.

단계 3: K-라인 배열 데이터를 변환

# Convert the K-line array into an array of highest price, lowest price, and closing price, for conversion to numpy.array
def get_data(bars):
    arr = []
    for i in bars:
        arr.append(i['Close'])
    return arr

여기 우리는 get_data 함수를 만들었습니다. 이 함수의 목적은 일반적인 K-line 배열을 numpy 형식의 데이터로 처리하는 것입니다. 입력 매개 변수는 K-line 배열이고 출력 결과는 numpy 형식의 처리 된 데이터입니다.

단계 4: 위치 데이터를 얻으십시오

# Get the number of positions
def get_position ():
     # Get position
     position = 0 # The number of assigned positions is 0
     position_arr = _C (exchange.GetPosition) # Get array of positions
     if len (position_arr)> 0: # If the position array length is greater than 0
         for i in position_arr:
             if i ['ContractType'] == 'rb000': # If the position symbol is equal to the subscription symbol
                 if i ['Type']% 2 == 0: # If it is long position
                     position = i ['Amount'] # Assigning a positive number of positions
                 else:
                     position = -i ['Amount'] # Assigning a negative number of positions
     return position

포지션 상태는 전략 논리를 포함합니다. 우리의 첫 번째 10 수업은 항상 가상 포지션을 사용했지만 실제 거래 환경에서 포지션 방향, 포지션 이익과 손실, 포지션 수 등을 포함하여 실제 포지션 정보를 얻기 위해 GetPosition 함수를 사용하는 것이 좋습니다.

단계 5: 데이터를 얻으십시오

exchange.SetContractType('rb000') # Subscribe the futures varieties
     bars_arr = exchange.GetRecords() # Get K line array
     if len(bars_arr) < 22: # If the number of K lines is less than 22
         return

데이터를 획득하기 전에 먼저 SetContractType 함수를 사용하여 관련 선물 품종을 구독해야합니다. FMZ는 모든 중국 상품 선물 품종을 지원합니다. 선물 기호에 구독 한 후 배열을 반환하는 K-라인 데이터를 얻기 위해 GetRecords 함수를 사용할 수 있습니다.

단계 6: 데이터를 계산합니다.

np_arr = np.array (get_data (bars_arr)) # Convert closing price array
sma13 = talib.SMA (np_arr, 130) [-9] # chin
sma8 = talib.SMA (np_arr, 80) [-6] # teeth
sma5 = talib.SMA (np_arr, 50) [-4] # upper lip
current_price = bars_arr [-1] ['Close'] # latest price

태리브 라이브러리를 사용하여 SMA를 계산하기 전에, 당신은 보통 K-라인 배열을 Numpy 데이터로 처리하기 위해 numpy 라이브러리를 사용해야합니다. 그 다음 해마, 치아 및 악어 라인의 상唇을 별도로 얻으십시오. 또한, 가격 매개 변수는 주문을 할 때 전달되어야하므로 K-라인 배열의 폐쇄 가격을 사용할 수 있습니다.

단계 7: 주문

position = get_position ()
if position == 0: # If there is no position
     if current_price> sma5: # If the current price is greater than the upper lip
         exchange.SetDirection ("buy") # Set the trading direction and type
         exchange.Buy (current_price + 1, 1) # open long position order
     if current_price <sma13: # If the current price is less than the chin
         exchange.SetDirection ("sell") # Set the trading direction and type
         exchange.Sell (current_price-1, 1) # open short position order
    
if position> 0: # If you have long positions
     if current_price <sma8: # If the current price is less than teeth
         exchange.SetDirection ("closebuy") # Set the trading direction and type
         exchange.Sell (current_price-1, 1) # close long position

if position <0: # If you have short position
     if current_price> sma8: # If the current price is greater than the tooth
         exchange.SetDirection ("closesell") # Set the trading direction and type
         exchange.Buy (current_price + 1, 1) # close short position

주문을 하기 전에 실제 포지션을 얻어야 합니다. 앞서 정의한 get_position 함수는 실제 포지션 수를 반환합니다. 현재 포지션이 길다면 양수를 반환합니다. 현재 포지션이 짧다면 음수를 반환합니다. 포지션이 없다면 0을 반환합니다. 마지막으로, 구매 및 판매 함수는 위의 거래 논리에 따라 주문을 배치하는 데 사용됩니다. 그러나 이 전에 거래 방향과 유형도 설정해야합니다.

전체 전략

'' 'backtest
start: 2019-01-01 00:00:00
end: 2020-01-01 00:00:00
period: 1h
exchanges: [{"eid": "Futures_CTP", "currency": "FUTURES"}]
'' '

import talib
import numpy as np


# Convert the K-line array into an array of highest price, lowest price, and closing price, used to convert to numpy.array type data
def get_data (bars):
    arr = []
    for i in bars:
        arr.append (i ['Close'])
    return arr


# Get the number of positions
def get_position ():
    # Get position
    position = 0 # The number of assigned positions is 0
    position_arr = _C (exchange.GetPosition) # Get array of positions
    if len (position_arr)> 0: # If the position array length is greater than 0
        for i in position_arr:
            if i ['ContractType'] == 'rb000': # If the position symbol is equal to the subscription symbol
                if i ['Type']% 2 == 0: # If it is long
                    position = i ['Amount'] # Assign a positive number of positions
                else:
                    position = -i ['Amount'] # Assign a negative number of positions
    return position
    
    

# Strategy main function
def onTick ():
    # retrieve data
    exchange.SetContractType ('rb000') # Subscribe to futures varieties
    bars_arr = exchange.GetRecords () # Get K line array
    if len (bars_arr) <22: # If the number of K lines is less than 22
        return
    
    # Calculation
    np_arr = np.array (get_data (bars_arr)) # Convert closing price array
    sma13 = talib.SMA (np_arr, 130) [-9] # chin
    sma8 = talib.SMA (np_arr, 80) [-6] # teeth
    sma5 = talib.SMA (np_arr, 50) [-4] # upper lip
    current_price = bars_arr [-1] ['Close'] # latest price

    position = get_position ()
    if position == 0: # If there is no position
        if current_price> sma5: # If the current price is greater than the upper lip
            exchange.SetDirection ("buy") # Set the trading direction and type
            exchange.Buy (current_price + 1, 1) # open long position order
        if current_price <sma13: # If the current price is less than the chin
            exchange.SetDirection ("sell") # Set the trading direction and type
            exchange.Sell (current_price-1, 1) # open short position order
        
    if position> 0: # If you have long positions
        if current_price <sma8: # If the current price is less than teeth
            exchange.SetDirection ("closebuy") # Set the trading direction and type
            exchange.Sell (current_price-1, 1) # close long position

    if position <0: # If you have short positions
        if current_price> sma8: # If the current price is greater than the tooth
            exchange.SetDirection ("closesell") # Set the trading direction and type
            exchange.Buy (current_price + 1, 1) # close short position

            
# Program main function
def main ():
    while True: # loop
        onTick () # execution strategy main function
        Sleep (1000) # sleep for 1 second

직접 아래 링크를 클릭하면 구성 없이 전체 전략을 복사할 수 있습니다:https://www.fmz.com/strategy/199025

악어 거래 규칙의 가장 큰 역할은 현재의 시장 가격 변화와 상관없이 거래 할 때 시장과 같은 방향을 유지하고 통합 시장이 나타날 때까지 이익을 계속하는 데 도움이됩니다. 악어 라인은 다른 MACD 및 KDJ 지표와 함께 잘 사용될 수 있습니다.


관련

더 많은