# 我们用fmz做了在线的一个网格交易回测功能

Author: 永赢量化-1, Created: 2020-10-18 23:56:01, Updated:

### 回到原点

``````self.grid_setting = {
"min_price": min_price,
"max_price": max_price,
"grid_diff": grid_diff,
"re_diff": grid_diff,
"total_amount_B": total_amount_B
}
``````

``````    def bus(self):
params = gen_params(self.begin, self.end, self.currency, self.balance, self.stocks)
done = self.train()
benefit_cal = self.cal_benefit(ret,done)
result = {}
result['done'] = done
result['ret'] = benefit_cal
return result
``````
• 通过刚才的gen_params函数获取fmz的回测配置
• 跑训练函数
• 根据fmz返回的数据结构，计算收益率和显示交易记录

``````  def cal_benefit(self,ret,done):
#计算相隔多少天
day_begin =  datetime.datetime.strptime(self.begin, '%Y-%m-%d %H:%M:%S')
day_end =  datetime.datetime.strptime(self.end, '%Y-%m-%d %H:%M:%S')
days = (day_end - day_begin).days
begin = ret.iloc[0].net
end = ret.iloc[-1].net
fee = ret.iloc[-1].fee
#计算一共多少次套利
df = pd.DataFrame(done)
#如果没有成交记录
if len(done) == 0:
benefit_cal = {}
benefit_cal['benefit'] = 0
benefit_cal['count'] = 0
benefit_cal['fee'] = 0
benefit_cal['benefit_p'] = 0
return benefit_cal

sell_count = len(df[df['type'] == 'sell'])
benefit = count * self.grid_diff * float(done[0]['amount'])
benefit_cal = {}
benefit_cal['benefit']= benefit
benefit_cal['count']= count
benefit_cal['fee']= fee
print(benefit_cal)
per = benefit / self.total_amount_B * 360 / days
print(per)
benefit_cal['benefit_p']= round( per , 4)
return benefit_cal
``````

### 采用挂单检查的思路进行

• 首先根据用户的参数初始化网格
• 初次挂单
• 定时检查挂单的成交情况，根据买卖单再重新挂单
``````          while True:
Sleep(1000 * 60 * 5)
if 'refreash_data_finish!' != mid.refreash_data():
continue
# 初始化网格
if not init_flag:
cur_price = mid.ticker['Last']
grid_list = grid.cal_grid_list(cur_price)
init_flag = True

# 开始挂单
if not place_flag:
grid.place_orders()
place_flag = True

# 开始检查订单状态及时挂单
grid.check_order_update()
done = grid.done
``````

More