바이낸스 선물거래에서 사용할 수 있는 페어트레이딩 전략(Pair Trading)의 예제입니다 !
import ccxt
import numpy as np
import pandas as pd
api_key = "your_api_key"
secret_key = "your_secret_key"
exchange = ccxt.binance({
'apiKey': api_key,
'secret': secret_key,
'enableRateLimit': True,
})
def get_historical_data(pair, timeframe, since):
bars = exchange.fetch_ohlcv(pair, timeframe, since)
data = pd.DataFrame(bars, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
return data
def calculate_spread(asset1, asset2):
spread = asset1['close'] / asset2['close']
return spread
def pair_trading(asset1_data, asset2_data, entry_threshold, exit_threshold, stop_loss, take_profit):
spread = calculate_spread(asset1_data, asset2_data)
spread_mean = spread.mean()
spread_std = spread.std()
long_entry = spread_mean + entry_threshold * spread_std
short_entry = spread_mean - entry_threshold * spread_std
long_exit = spread_mean + exit_threshold * spread_std
short_exit = spread_mean - exit_threshold * spread_std
position = 0
entry_price = 0
for i in range(len(asset1_data)):
if position == 0:
if spread[i] > long_entry:
position = 1
entry_price = spread[i]
print("Long position opened at", entry_price)
elif spread[i] < short_entry:
position = -1
entry_price = spread[i]
print("Short position opened at", entry_price)
elif position == 1:
if spread[i] < long_exit or spread[i] < entry_price * (1 - stop_loss) or spread[i] > entry_price * (1 + take_profit):
position = 0
print("Long position closed at", spread[i])
elif position == -1:
if spread[i] > short_exit or spread[i] > entry_price * (1 + stop_loss) or spread[i] < entry_price * (1 - take_profit):
position = 0
print("Short position closed at", spread[i])
asset1 = "BTC/USDT"
asset2 = "ETH/USDT"
timeframe = "1h"
since = exchange.parse8601("2022-01-01T00:00:00Z")
asset1_data = get_historical_data(asset1, timeframe, since)
asset2_data = get_historical_data(asset2, timeframe, since)
entry_threshold = 1
exit_threshold = 0.5
stop_loss = 0.03
take_profit = 0.03
pair_trading(asset1_data, asset2_data, entry_threshold, exit_threshold, stop_loss, take_profit)
반응형