Python 自动交易策略:期货市场数据分析与实时监控
以下是一个基于 Python 编写的自动交易策略的基本框架,可以用于国内期货市场的数据分析和交易。该策略基于多图共振趋势方向,并结合 KD 和 RSI 指标进行交易决策。
import ccxt
import time
# 连接交易所
exchange = ccxt.okex()
symbol = 'BTC/USD'
# 获取历史K线数据
timeframe = '15m'
limit = 1000 # 获取最近 1000 根 K 线数据
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit)
# 定义指标参数
k = 18
d = 3
rsi_period = 5
rsi_upper = 70
rsi_lower = 30
# 计算指标
def calculate_indicators(ohlcv):
# 计算 KD 指标
highest_high = max([x[2] for x in ohlcv[-k:]])
lowest_low = min([x[3] for x in ohlcv[-k:]])
rsv = (ohlcv[-1][4] - lowest_low) / (highest_high - lowest_low) * 100
k_value = 2/3 * ohlcv[-2][5] + 1/3 * rsv
d_value = 2/3 * ohlcv[-2][6] + 1/3 * k_value
j_value = 3 * k_value - 2 * d_value
# 计算 RSI 指标
closes = [x[4] for x in ohlcv[-rsi_period:]]
up_moves = [x for x in closes[1:] - closes[:-1] if x > 0]
down_moves = [abs(x) for x in closes[1:] - closes[:-1] if x < 0]
rs = sum(up_moves) / sum(down_moves)
rsi_value = 100 - 100 / (1 + rs)
return k_value, d_value, j_value, rsi_value
# 判断是否买入
def should_buy(ohlcv):
if ohlcv[-1][4] > ohlcv[-2][4] and ohlcv[-2][4] > ohlcv[-3][4]:
# 最近三根 K 线呈现上涨趋势,判断是否突破平台顶部高点
platform_high = max([x[2] for x in ohlcv[:-3] if x[2] == x[3]])
if ohlcv[-1][2] > platform_high:
# 突破平台顶部高点,判断是否符合金叉共振信号
k_value, d_value, j_value, rsi_value = calculate_indicators(ohlcv)
if k_value > d_value and ohlcv[-1][4] > ohlcv[-2][4] and rsi_value > rsi_upper:
return True
return False
# 判断是否加仓
def should_add_position(ohlcv, positions):
if len(positions) > 0 and positions[-1]['type'] == 'long':
# 已经持有多仓,判断是否符合加仓条件
platform_low = min([x[3] for x in ohlcv[:-3] if x[2] == x[3]])
if ohlcv[-1][4] > platform_low:
# 突破平台底部线,判断是否符合加仓信号
k_value, d_value, j_value, rsi_value = calculate_indicators(ohlcv)
if k_value > d_value and ohlcv[-1][4] > ohlcv[-2][4] and ohlcv[-2][4] > ohlcv[-3][4]:
return True
return False
# 判断是否卖出
def should_sell(ohlcv, positions):
if len(positions) > 0:
if positions[-1]['type'] == 'long':
# 已经持有多仓,判断是否符合止盈或止损条件
if ohlcv[-1][4] <= 0.99 * positions[-1]['entry_price']:
return True
if ohlcv[-1][4] <= 0.99 * positions[-1]['stop_loss']:
return True
elif positions[-1]['type'] == 'short':
# 已经持有空仓,判断是否符合止盈或止损条件
if ohlcv[-1][4] >= 1.01 * positions[-1]['entry_price']:
return True
if ohlcv[-1][4] >= 1.01 * positions[-1]['stop_loss']:
return True
return False
# 判断是否平仓
def should_close_position(ohlcv, positions):
if len(positions) > 0:
if positions[-1]['type'] == 'long':
# 已经持有多仓,判断是否符合平仓条件
if should_sell(ohlcv, positions):
return True
elif positions[-1]['type'] == 'short':
# 已经持有空仓,判断是否符合平仓条件
if should_sell(ohlcv, positions):
return True
return False
# 运行策略
positions = []
while True:
# 获取最新 K 线数据
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit)[-k-rsi_period:]
# 判断是否需要买入或加仓
if should_buy(ohlcv):
if len(positions) == 0:
# 开仓
entry_price = ohlcv[-1][4]
stop_loss = 0.99 * entry_price
positions.append({'type': 'long', 'entry_price': entry_price, 'stop_loss': stop_loss})
exchange.create_order(symbol, 'market', 'buy', 2)
elif should_add_position(ohlcv, positions):
# 加仓
entry_price = ohlcv[-1][4]
stop_loss = 0.99 * entry_price
positions.append({'type': 'long', 'entry_price': entry_price, 'stop_loss': stop_loss})
exchange.create_order(symbol, 'market', 'buy', 1)
# 判断是否需要卖出或平仓
if should_close_position(ohlcv, positions):
# 平仓
exchange.create_order(symbol, 'market', 'sell', 2)
positions = []
# 判断是否需要停止运行
if len(positions) > 0:
total_value = exchange.fetch_balance()[symbol.split('/')[0]]['total']
position_value = sum([p['entry_price'] * 2 for p in positions])
if position_value / total_value < 0.8:
# 整体仓位回撤 20%,平掉全部仓位停止运行
exchange.create_order(symbol, 'market', 'sell', 2)
positions = []
break
# 等待下一根 K 线
time.sleep(900) # 等待 15 分钟
策略逻辑:
- 数据获取: 从期货交易所获取 15 分钟 K 线数据,并根据最近 1000 根 K 线数据进行分析。
- 指标计算: 计算 KD 指标和 RSI 指标,并根据指标值判断交易信号。
- 交易决策:
- 买入: 当 60 分钟、30 分钟和 15 分钟 K 线图呈现上涨趋势,且突破平台顶部高点,同时 KD 和 RSI 指标产生金叉共振信号时,买入 2 手。
- 加仓: 当持有多仓,且突破平台底部线,同时 KD 和 RSI 指标满足金叉共振条件时,加仓 1 手。
- 卖出: 当持有多仓或空仓,价格回撤 1% 时,卖出平仓。
- 止损: 当持有多仓或空仓,价格反向回撤 1% 时,止损平仓。
- 风险控制: 当整体仓位回撤 20% 时,平掉所有仓位并停止运行策略。
注意:
- 本代码仅供参考,需要根据实际情况进行修改和完善。
- 交易策略的性能与参数设置、市场波动和交易所的稳定性等因素密切相关。
- 在使用任何自动交易策略之前,请务必进行充分的回测和风险评估。
- 投资有风险,入市需谨慎。
原文地址: https://www.cveoy.top/t/topic/og6K 著作权归作者所有。请勿转载和采集!