如何在策略中读写Excel文件
The sample code below shows how to read from Excel file and write to it while a strategy is running. It reades two sma lengths from the SampleBook.xlsx file in the OnStrategyStart method and writes the last bar’s close price to the Excel file in the OnBar method.
本示例以下代码显示了当策略运行时如何从Excel文件读取并存盘。示例从SampleBook.xlsx文件的OnStrategyStart中读取了2个SMA时间周期,并在OnBar中把最新的bar收盘价编写进Excel文件。
To build the sample you should add a reference to the Interop.Excel.dll, using the following steps:
- using System;
- using System.Drawing;
using OpenQuant.API;
using OpenQuant.API.Indicators;
using Interop.Excel;
public class MyStrategy : Strategy
{
SMA sma1;
SMA sma2;
Workbook workbook;
Worksheet worksheet;
public override void OnStrategyStart()
{
// open Excel file 打开Excel文件
Application excel = new Application();
workbook = excel.Workbooks.Open(@"C:\Users\s.b\Documents\SampleBook.xlsx", 0, false,
5, “”, “”, true, Interop.Excel.XlPlatform.xlWindows, “\t”, false, false, 0, true, null,
null);
Sheets sheets = workbook.Worksheets;
worksheet = (Worksheet)sheets.get_Item(1);
// read A1 and A2 values 读取A1和A2值
double length1 = (double)worksheet.get_Range("A1", "A1").Value2;
double length2 = (double)worksheet.get_Range("A2", "A2").Value2;
//
sma1 = new SMA(Bars, (int)length1);
sma2 = new SMA(Bars, (int)length2);
}
public override void OnBar(Bar bar)
{
worksheet.get_Range(“B1”, “B1”).Value2 = bar.Close;
}
public override void OnStrategyStop()
{
// save and close the workbook 保存并关闭工作簿(Excel文件)
workbook.Save();
workbook.Close(true, null, null);
}
}
为了建立示例你应该增加一个Interop.Excel.dll文件的引用,使用以下方法:
locate the Interop.Excel.dll file at “[Installation Directory]\Framework\bin” folder
打开[Installation Directory]\Framework\bin文件夹,找到Interop.Excel.dll文件
copy it to the “[Installation Directory]\bin” folder
把它复制到 [Installation Directory]\bin文件夹
from the main menu go to Tools -> Options, in the opened Options dialog click “Projects and Solutions” node and select “Build” node. Click “Add” button, choose “.NET…” option and choose the Interop.Excel.dll file.
从主菜单找到Tools -> Options,在打开的Options对话框中点击Projects and Solutions节点选择Build节点。单击Add按钮,选择“.NET…”选项再选择Interop.Excel.dll 文件。