期货的网格交易是常见的操作, 但是调试代码比较麻烦,因为没法动态实时生成价格, 本代码模拟了期货的动态实时价格生成, 根据先设置的规则, 程序会自动进行档位调整。
完整代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 模拟价格变化递归阻塞
import time
import random
START_PRICE = 50 # 起始价位
GRID_AMOUNT = 10 # 网格在多头、空头方向的格子(档位)数量
grid_region_long = [0.05] * GRID_AMOUNT # 多头每格价格跌幅(网格密度)
grid_region_short = [0.05] * GRID_AMOUNT # 空头每格价格涨幅(网格密度)
grid_volume_long = [i for i in range(GRID_AMOUNT + 1)] # 多头每格持仓手数
grid_volume_short = [i for i in range(GRID_AMOUNT + 1)] # 空头每格持仓手数
grid_prices_long = [reduce(lambda p, r: p * (1 - r), grid_region_long[:i], START_PRICE) for i in
range(GRID_AMOUNT + 1)] # 多头每格的触发价位列表
grid_prices_short = [reduce(lambda p, r: p * (1 + r), grid_region_short[:i], START_PRICE) for i in
range(GRID_AMOUNT + 1)] # 空头每格的触发价位列表
print("多头价格表:")
print(grid_prices_long)
print("空头价格表:")
print(grid_prices_short)
# 模拟期货每隔1秒生成一个价格
class Api(object):
def __init__(self, frequency=1, price=100, scale=0.5):
self.frequency = frequency
self.price = price
self.scale = scale
def wait_update(self):
time.sleep(self.frequency)
plus = random.uniform(1, 10)
if random.randint(0, 1) ==0 :
self.price += self.scale*plus
else:
self.price -= self.scale*plus
def last_price(self):
return self.price
api = Api(3, START_PRICE) #初始化价格生成,新建一个事例赋给变量 api
def wait_price(layer):
if(layer >0) or api.last_price() <= grid_prices_long[1]: # 多头
while True:
print("-----当前在多头,第%d 层" % (layer))
print("最新价: %f, 下一层价: %f" % (api.last_price(), grid_prices_long[layer+1]))
api.wait_update()
if layer < GRID_AMOUNT and api.last_price() <= grid_prices_long[layer+1]:
print("最新价: %f, 进入: 多头第 %d 档" % (api.last_price(), layer + 1))
wait_price(layer + 1)
print("已回到多头,第 %d 档" % (layer))
if api.last_price() > grid_prices_long[layer]:
print("最新价: %f, 回退到: 多头第 %d 档" % (api.last_price(), layer))
return
elif layer <0 or api.last_price >= grid_region_short[1]: #空头
layer = -layer
while True:
api.wait_update()
print("-----当前在空头,第%d 层" % (layer))
print("最新价: %f, 下一层价: %f" % (api.last_price(), grid_prices_short[layer+1]))
if layer < GRID_AMOUNT and api.last_price() >= grid_prices_short[layer+1]:
print("最新价: %f, 进入: 空头第 %d 档" % (api.last_price(), layer + 1))
wait_price(-(layer + 1))
print("已回到空头,第 %d 档" % (layer))
if api.last_price() < grid_prices_short[layer]:
print("最新价: %f, 回退到: 空头第 %d 档" % (api.last_price(), layer))
return
while True:
api.wait_update()
print("第一个价格:%f" % (api.last_price()))
wait_price(0)
程序主要的过程如下:
- 初始化价格生成对象
api = Api(3, START_PRICE)
- 进入第一个循环等待价格变化
while True:
api.wait_update()
print("第一个价格:%f" % (api.last_price()))
wait_price(0)
write_price 是一个递归阻塞的函数, 层数是我们设置的 GRID_AMOUNT 价格档位,当价格到达合适档位就会进入对应的层, 如果价格没有达到就继续停留在本层。
转载请注明:大后端 » python 动态生成期货价格+模拟网格交易过程