├── .gitattributes ├── .gitignore ├── QuantLib ├── QuantLib.py └── __init__.py ├── README.md ├── __init__.py ├── _pyktlib.pyd ├── agent.py ├── agent_gui.py ├── backtest.py ├── base.py ├── berm_swaption.py ├── candle_graph_demo.py ├── chart.py ├── ctp_api.py ├── ctp_emulator.py ├── data_handler.py ├── data_saver.py ├── decorator.py ├── docs ├── X-Speed交易系统应用程序接口说明文档.pdf ├── 极速交易平台X-Speed API技术开发指南.pdf └── 注意:API_v15 开发前必读事项.txt ├── eventEngine.py ├── fix_db_data.py ├── lts_api.py ├── misc.py ├── order.py ├── pl_reconcile.py ├── pyktlib.py ├── save_data_tool.py ├── sec_bits.py ├── strat_dual_thrust.py ├── strategy.py ├── strats ├── 60-The Volatility (Regime) Switch Indicator.pdf ├── Arma11.pdf ├── Binary_if_3min.txt ├── CU_5mins_UpperBand_LowerBand.txt ├── EmpiricalModeDecomposition.pdf ├── Exit Strategy ATR Ratchet.doc ├── IF_1min_MACD.txt ├── IF_Range_Breakout_1mins.txt ├── Kurtosis-Skewing交易策略.txt ├── K线形态多空策略源码.txt ├── MR_Swing_NAAIM_2010.pdf ├── OLS交易系统策略.txt ├── PTA_15mins_MA.txt ├── RU_1D_HL.txt ├── Swing │ ├── Bollinger Bands_Stop_v2 .mq4 │ ├── Fisher.mq4 │ ├── Fisher_no_repainting.mq4 │ ├── Heiken_Ashi_Smoothed.mq4 │ ├── indicators │ │ ├── Bollinger Bands_Stop_v2 .mq4 │ │ ├── Fisher.mq4 │ │ └── Heiken_Ashi_Smoothed (1).ex4 │ └── template │ │ └── template_name.tpl ├── TS交易之王MACD指标模型实例.txt ├── Trend Quality.pdf ├── asctrend systems │ ├── ASCTrend.pdf │ ├── ASCTrend_Sound.mq4.mq4 │ ├── ATR Channels.mq4 │ ├── ATRStops_v1_separate.mq4 │ ├── ATRTrailStop_v3.mq4 │ ├── ATR_Stop.mq4 │ ├── Algo-Trading-Intro-2013-Steinki-Session-1.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-10.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-11.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-12.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-2.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-3.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-4.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-5.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-6.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-7.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-8.pdf │ ├── Algo-Trading-Intro-2013-Steinki-Session-9.pdf │ ├── AscTrend2.mq4 │ ├── Delta.mq4 │ ├── Fisher_exit.mq4 │ ├── Fisher_v1.mq4 │ ├── KGSP.mq4 │ ├── LabTrend1_v1.mq4 │ ├── LabTrend2_v1.mq4 │ ├── LabTrend3_v1.mq4 │ ├── NRTR Line.mql │ ├── NRTR WATR.mql │ ├── NRTR.mql │ ├── NRTR_ColorLine_my.mql │ ├── NRTR_Line1_separate.mq4 │ ├── NRTR_dots1_separate.mq4 │ ├── PriceChannel_Stop_v1.mq4 │ ├── RSIFilter_v1.mq4 │ ├── RoundPriceNE_big_separate.mq4 │ ├── RoundPriceNE_pips.mq4 │ ├── TrendStrength_v2.mq5 │ ├── WPRfast.mql │ ├── WPRslow.mql │ ├── asctrendbuysellexpert_v1.7.mq4 │ └── iTrend_hist.mq4 ├── brainstorm_intraday_trade.txt ├── if_1mins_atr.txt ├── if_3mins_cs.txt ├── if_5_mins_yellow_qs.txt ├── if_5mins_bollzd.txt ├── if_5mins_ef.txt ├── if_5mins_qs.txt ├── if_5mins_td.txt ├── if_5mins布林带策略.txt ├── if_5mins高低点突破策略.txt ├── if_5mis日内高低突破策略.txt ├── left_right_hand.txt ├── mixed collections.txt ├── pta_30_uplowbas.txt ├── pta_30mins_bdking.txt ├── rb_5mins_breakout.txt ├── rb_60_tp.txt ├── research reports │ ├── 20150813-广发证券-另类交易策略之二十八:论RSI指标在股指期货日内交易中的使用.pdf │ ├── 20170104-东方证券-《衍生品研究系列之四》:基于单特征因子的隐马尔科夫模型在商品期货上的应用.pdf │ ├── 20170314-广发证券-交易性择时策略研究之九:利用均线间距变化提前预判趋势.pdf │ ├── 20180810-东方证券-东方证券衍生品系列研究之(十一):商品基本面量化研究之铁矿石.pdf │ ├── 20181101-海通证券-海通证券金融工程专题报告:高频量价因子在股票与期货中的表现.pdf │ ├── 中信建投_20160118_大宗商品价格波动四周期嵌套模型的构建:大宗商品周期研究.pdf │ ├── 华泰期货_20170825_华泰期货量化专题报告:贝叶斯线性回归在期货交易中的应用.pdf │ ├── 华泰期货_20171124_华泰期货量化策略专题报告:CTA量化策略因子系列(四)策略因子组合与择时.pdf │ ├── 华泰证券_20130123_股指期货程序化交易研究之九:Pivot+Point策略.pdf │ ├── 商品期货CTA专题报告(三):策略的趋势过滤-20170321-天风证券-14页.pdf │ ├── 商品期货CTA专题报告(四):库存基本面与动量技术面共振的投资策略-20180105-天风证券-26页.pdf │ ├── 天风证券_20170914_天风证券金融工程:利用组合优化构建投资组合.pdf │ ├── 天风证券_20170921_天风证券金工专题报告:基于动态风险控制的组合优化模型.pdf │ ├── 广发证券_20160318_广发证券FICC业务系列报告之三:商品期货跨市场套利解决方案.pdf │ ├── 广发证券_20160601_精益求精:基于动量反转敏感度系数筛选的优化策略.pptx │ ├── 方正证券_20170918_方正证券CTA专题研究:基于平稳过程的CTA策略增强框架.pdf │ ├── 申万宏源_20170607_申万宏源趋势因子:动量与反转效应的结合.pdf │ ├── 银河证券_20160317_银河证券β趋势控制策略(二):大宗商品的投资方式.pdf │ ├── 银河证券_20160412_β趋势控制策略(三):拐点的仓位控制.pdf │ ├── 银河证券_20160706_金融工程-衍生品投机:β趋势控制策略(四)_提取震荡行情的回报.pdf │ └── 银河证券_20160831_金融工程-衍生品投机:β趋势控制策略(五)_震荡策略的设计与因子分析.pdf ├── ru_15mins.txt ├── sr_5mins_hl_atr.txt ├── ssto交易系统策略.txt ├── thermostat系统源码.txt ├── turtle_soup_source.txt ├── 一个稳定盈利的日内交易系统.txt ├── 一致趋势下的股指期货交易策略——股指期货短线交易策略研究系列之三.pdf ├── 上唇下鄂指标+交易策略.txt ├── 交易开拓者日内高低点突破交易系统.txt ├── 全自动动态突破型交易系统.txt ├── 分形操作突破法.txt ├── 协整理论在期指套利中的运用及策略.txt ├── 回抽开仓多空模型.txt ├── 完善的日内交易系统框架源码.txt ├── 开拓者道氏理论交易策略.txt ├── 开盘突破日内策略.txt ├── 日内开盘区高低点机械突破交易系统.txt ├── 日内高低点突破交易系统.txt ├── 盈利的交易系统.txt ├── 盈多亏交易策略.txt ├── 突破+穿越追涨杀跌法交易策略.txt ├── 简单的波动性突破系统.txt ├── 简单突破系统(Hans交易法).txt ├── 网格交易.txt ├── 美林证券交易大师交易策略模型源码.txt ├── 股指3分钟日内支撑阻力位突破交易策略.txt ├── 超级日内组合系统.txt ├── 逐风破浪交易系统.txt ├── 震荡+趋势混合策略恒温器策略.txt ├── 顺势指标交易策略源码.txt ├── 顺势模型源码.txt └── 飞天创富系统策略.txt ├── test_data.py ├── tools ├── BSHistVolTool.py ├── arboptimizer.py ├── bsopt.py ├── candle_graph_demo.py ├── chart.py ├── fix_db_data.py ├── optstrat.py ├── pl_reconcile.py ├── process_hist_data.py ├── quote_example.cpp ├── save_data_tool.py ├── split_file.py ├── test_chart.py ├── test_option_gui.py ├── trade_emulator.py ├── update_contract_table.py └── yahoo_mysql_importer.py ├── trade_emulator.py ├── update_contract_table.py ├── wind_data.py └── yahoo_mysql_importer.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # ========================= 18 | # Operating System Files 19 | # ========================= 20 | 21 | # OSX 22 | # ========================= 23 | 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must ends with two \r. 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | -------------------------------------------------------------------------------- /QuantLib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/QuantLib/__init__.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 基于pyctp接口,使用tkinter作为GUI的python交易平台 2 | 3 | 主要功能: 4 | 5 | (1)本地仓位管理,保证金计算,开仓平昨平今的逻辑 6 | 7 | (2) 增加trade level以支持多腿下单,屏蔽开仓平仓逻辑,可以做跨合约套利 8 | 9 | (3) 支持多品种,多策略同时运行并可手动更改交易参数 10 | 11 | (4) 策略层增加tradepos level以便对trail profit, stop loss等增加支持 12 | 13 | (5) 基于mySQL数据库,对实时数据tick,minute,daily进行保存 14 | 15 | (6) 具有option pricng C++库 16 | 17 | (7) 具有option模块和相应GUI(逐步扩展中) 18 | 19 | (8) 具有分钟级回测CTA策略 20 | 21 | (9) 支持仿真交易(历史数据paper trading)和实时模拟交易(实时数据paper trading) 22 | 23 | 有兴趣合作联系 24 | 25 | QQ: 1940877918 26 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/__init__.py -------------------------------------------------------------------------------- /_pyktlib.pyd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/_pyktlib.pyd -------------------------------------------------------------------------------- /candle_graph_demo.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY 3 | from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc 4 | 5 | def show_candlestick(ticker, startD, endD): 6 | mondays = WeekdayLocator(MONDAY) # major ticks on the mondays 7 | alldays = DayLocator() # minor ticks on the days 8 | weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 9 | dayFormatter = DateFormatter('%d') # e.g., 12 10 | 11 | quotes = quotes_historical_yahoo_ohlc(ticker, startD, endD) 12 | if len(quotes) == 0: 13 | raise SystemExit 14 | 15 | fig, ax = plt.subplots() 16 | fig.subplots_adjust(bottom=0.2) 17 | #ax.xaxis.set_major_locator(mondays) 18 | #ax.xaxis.set_minor_locator(alldays) 19 | #ax.xaxis.set_major_formatter(weekFormatter) 20 | #ax.xaxis.set_minor_formatter(dayFormatter) 21 | 22 | #plot_day_summary(ax, quotes, ticksize=3) 23 | candlestick_ohlc(ax, quotes, width=0.6) 24 | 25 | ax.xaxis_date() 26 | ax.autoscale_view() 27 | plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') 28 | 29 | plt.show() -------------------------------------------------------------------------------- /chart.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import numpy as np 3 | from matplotlib import verbose, get_cachedir 4 | from matplotlib.dates import date2num 5 | from matplotlib.cbook import iterable, mkdirs 6 | from matplotlib.collections import LineCollection, PolyCollection 7 | from matplotlib.colors import colorConverter 8 | from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT 9 | from matplotlib.patches import Rectangle 10 | from matplotlib.transforms import Affine2D 11 | 12 | def cchart(ax, ohlc_df, width=4, 13 | colorup='k', colordown='r', 14 | alpha=0.75, 15 | ): 16 | """ 17 | Represent the open, close as a bar line and high low range as a 18 | vertical line. 19 | ax : an Axes instance to plot to 20 | width : the bar width in points 21 | colorup : the color of the lines where close >= open 22 | colordown : the color of the lines where close < open 23 | alpha : bar transparency 24 | 25 | return value is lineCollection, barCollection 26 | """ 27 | 28 | # note this code assumes if any value open, close, low, high is 29 | # missing they all are missing 30 | 31 | delta = width/2. 32 | barVerts = [ ( (i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open) ) for i, open, close in zip(xrange(len(ohlc_df.open)), ohlc_df.open, ohlc_df.close) if open != -1 and close!=-1 ] 33 | 34 | #rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(ohlc_df.low)), ohlc_df.low, ohlc_df.high) if low != -1 ] 35 | rangeSegments = [ ((i, max(open, close)), (i, high)) for i, high, open, close in zip(xrange(len(ohlc_df.high)), ohlc_df.high, ohlc_df.open, ohlc_df.close) if high!=-1 ] 36 | rangeSegments2 = [ ((i, low), (i, min(open, close))) for i, low, open, close in zip(xrange(len(ohlc_df.low)), ohlc_df.low, ohlc_df.open, ohlc_df.close) if low!=-1] 37 | 38 | r,g,b = colorConverter.to_rgb(colorup) 39 | colorup = r,g,b,alpha 40 | r,g,b = colorConverter.to_rgb(colordown) 41 | colordown = r,g,b,alpha 42 | colord = { True : colorup, 43 | False : colordown, 44 | } 45 | colors = [colord[open5: 188 | ee.stop() 189 | break 190 | 191 | # 直接运行脚本可以进行测试 192 | if __name__ == '__main__': 193 | test() -------------------------------------------------------------------------------- /fix_db_data.py: -------------------------------------------------------------------------------- 1 | import mysqlaccess 2 | import misc 3 | import data_handler 4 | 5 | def filter_main_cont(sdate): 6 | insts, prods = mysqlaccess.load_alive_cont(sdate) 7 | main_cont = {} 8 | for pc in prods: 9 | main_cont[pc], exch = mysqlaccess.prod_main_cont_exch(pc) 10 | main_insts = [] 11 | for inst in insts: 12 | pc = misc.inst2product(inst) 13 | mth = int(inst[-2:]) 14 | if mth in main_cont[pc]: 15 | main_insts.append(inst) 16 | return main_insts 17 | 18 | def fix_daily_data(contlist, sdate, edate, is_forced=False): 19 | for inst in contlist: 20 | ddf = mysqlaccess.load_daily_data_to_df('fut_daily', inst, sdate, edate) 21 | mdf = mysqlaccess.load_min_data_to_df('fut_min', inst, sdate, edate, minid_start=300, minid_end = 2115) 22 | dailydata = data_handler.conv_ohlc_freq(mdf, 'D') 23 | for dd in dailydata.index: 24 | d = dd.date() 25 | dslice = dailydata.ix[dd] 26 | if (d not in ddf.index) or is_forced: 27 | ddata = {} 28 | ddata['date'] = d 29 | ddata['open'] = float(dslice.open) 30 | ddata['close'] = float(dslice.close) 31 | ddata['high'] = float(dslice.high) 32 | ddata['low'] = float(dslice.low) 33 | ddata['volume'] = int(dslice.volume) 34 | ddata['openInterest'] = int(dslice.openInterest) 35 | print inst, ddata 36 | mysqlaccess.insert_daily_data(inst, ddata, is_forced) 37 | 38 | def fix_daily_by_tick(contlist, sdate, edate, is_forced=False): 39 | res = {} 40 | for inst in contlist: 41 | product = misc.inst2product(inst) 42 | start_tick= 1500000 43 | end_tick = 2100000 44 | if product in misc.night_session_markets: 45 | start_tick = 300000 46 | elif product in ['IF','TF','IC','IH','T']: 47 | start_tick = 1515000 48 | end_tick = 2115000 49 | ddf = mysqlaccess.load_daily_data_to_df('fut_daily', inst, sdate, edate) 50 | tdf = mysqlaccess.load_tick_to_df('fut_tick', inst, sdate, edate, start_tick=start_tick, end_tick = end_tick) 51 | for d in list(set(tdf.date)): 52 | if (is_forced) or (d not in ddf.index) or (ddf.ix(d, 'open')==0): 53 | df = tdf[tdf['date']==d].sort(['tick_id']) 54 | ddata = {} 55 | ddata['date'] = d 56 | ddata['open'] = float(df.iloc[0].price) 57 | ddata['close'] = float(df.iloc[-1].price) 58 | ddata['high'] = float(df.iloc[-1].high) 59 | ddata['low'] = float(df.iloc[-1].low) 60 | ddata['volume'] = int(df.iloc[-1].volume) 61 | ddata['openInterest'] = int(df.iloc[-1].openInterest) 62 | print inst, ddata 63 | res[(inst,d)] = ddata 64 | mysqlaccess.insert_daily_data(inst, ddata, is_forced) 65 | return res 66 | 67 | 68 | -------------------------------------------------------------------------------- /pl_reconcile.py: -------------------------------------------------------------------------------- 1 | import order 2 | import agent 3 | import misc 4 | import csv 5 | 6 | def get_eod_positions(logfile): 7 | capital = 0.0; 8 | pos = {} 9 | with open(logfile, 'rb') as f: 10 | reader = csv.reader(f) 11 | for idx, row in enumerate(reader): 12 | if row[0] == 'capital': 13 | capital = float(row[1]) 14 | elif row[0] == 'pos': 15 | inst = row[1] 16 | plong = int(row[2]) 17 | pshort = int(row[3]) 18 | pclose = float(row[4]) 19 | pos[inst] = {'long': plong, 'short':pshort, 'close':pclose} 20 | return (capital, pos) 21 | 22 | def check_pnl(log_folder, sdate, edate): 23 | logfile = log_folder + 'EOD_Pos_' + sdate.strftime('%y%m%d')+'.csv' 24 | (s_capital, s_pos) = get_eod_positions(logfile) 25 | logfile = log_folder + 'EOD_Pos_' + edate.strftime('%y%m%d')+'.csv' 26 | (e_capital, e_pos) = get_eod_positions(logfile) 27 | instruments = agent.Instrument.create_instruments(s_pos.keys()) 28 | positions = dict([(inst, order.Position(instruments[inst])) for inst in s_pos]) 29 | order_list = order.load_order_list(edate, log_folder, positions) 30 | pnl_tday = 0.0 31 | pnl_yday = [(s_pos[inst]['long'] - s_pos[inst]['short'])*(e_pos[inst]['close']-s_pos[inst]['close'])*instruments[inst].multiple for inst in s_pos] 32 | print sum(pnl_yday), pnl_yday 33 | for o in order_list.values(): 34 | v = o.filled_volume 35 | inst = o.position.instrument.name 36 | if o.direction == misc.ORDER_SELL: 37 | v = -v 38 | pnl_tday += v * (e_pos[inst]['close'] - o.filled_price) * instruments[inst].multiple 39 | print pnl_tday 40 | 41 | -------------------------------------------------------------------------------- /pyktlib.py: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by SWIG (http://www.swig.org). 2 | # Version 3.0.4 3 | # 4 | # Do not make changes to this file unless you know what you are doing--modify 5 | # the SWIG interface file instead. 6 | 7 | 8 | 9 | 10 | 11 | from sys import version_info 12 | if version_info >= (2, 6, 0): 13 | def swig_import_helper(): 14 | from os.path import dirname 15 | import imp 16 | fp = None 17 | try: 18 | fp, pathname, description = imp.find_module('_pyktlib', [dirname(__file__)]) 19 | except ImportError: 20 | import _pyktlib 21 | return _pyktlib 22 | if fp is not None: 23 | try: 24 | _mod = imp.load_module('_pyktlib', fp, pathname, description) 25 | finally: 26 | fp.close() 27 | return _mod 28 | _pyktlib = swig_import_helper() 29 | del swig_import_helper 30 | else: 31 | import _pyktlib 32 | del version_info 33 | from _pyktlib import * 34 | try: 35 | _swig_property = property 36 | except NameError: 37 | pass # Python < 2.2 doesn't have 'property'. 38 | 39 | 40 | def _swig_setattr_nondynamic(self, class_type, name, value, static=1): 41 | if (name == "thisown"): 42 | return self.this.own(value) 43 | if (name == "this"): 44 | if type(value).__name__ == 'SwigPyObject': 45 | self.__dict__[name] = value 46 | return 47 | method = class_type.__swig_setmethods__.get(name, None) 48 | if method: 49 | return method(self, value) 50 | if (not static): 51 | object.__setattr__(self, name, value) 52 | else: 53 | raise AttributeError("You cannot add attributes to %s" % self) 54 | 55 | 56 | def _swig_setattr(self, class_type, name, value): 57 | return _swig_setattr_nondynamic(self, class_type, name, value, 0) 58 | 59 | 60 | def _swig_getattr_nondynamic(self, class_type, name, static=1): 61 | if (name == "thisown"): 62 | return self.this.own() 63 | method = class_type.__swig_getmethods__.get(name, None) 64 | if method: 65 | return method(self) 66 | if (not static): 67 | return object.__getattr__(self, name) 68 | else: 69 | raise AttributeError(name) 70 | 71 | def _swig_getattr(self, class_type, name): 72 | return _swig_getattr_nondynamic(self, class_type, name, 0) 73 | 74 | 75 | def _swig_repr(self): 76 | try: 77 | strthis = "proxy of " + self.this.__repr__() 78 | except: 79 | strthis = "" 80 | return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) 81 | 82 | try: 83 | _object = object 84 | _newclass = 1 85 | except AttributeError: 86 | class _object: 87 | pass 88 | _newclass = 0 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | # This file is compatible with both classic and new-style classes. 109 | 110 | 111 | -------------------------------------------------------------------------------- /save_data_tool.py: -------------------------------------------------------------------------------- 1 | import agent as agent 2 | import fut_api 3 | #import lts_api 4 | import logging 5 | import mysqlaccess 6 | import misc 7 | import Tkinter as tk 8 | import threading 9 | import ScrolledText 10 | import update_contract_table 11 | import sys 12 | import datetime 13 | import threading 14 | 15 | class TextHandler(logging.Handler): 16 | """This class allows you to log to a Tkinter Text or ScrolledText widget""" 17 | def __init__(self, text): 18 | # run the regular Handler __init__ 19 | logging.Handler.__init__(self) 20 | # Store a reference to the Text it will log to 21 | self.text = text 22 | 23 | def emit(self, record): 24 | msg = self.format(record) 25 | def append(): 26 | self.text.configure(state='normal') 27 | self.text.insert(tk.END, msg + '\n') 28 | self.text.configure(state='disabled') 29 | # Autoscroll to the bottom 30 | self.text.yview(tk.END) 31 | # This is necessary because we can't modify the Text from other threads 32 | self.text.after(0, append) 33 | 34 | def filter_main_cont(sdate): 35 | insts, prods = mysqlaccess.load_alive_cont(sdate) 36 | main_cont = {} 37 | for pc in prods: 38 | main_cont[pc], exch = mysqlaccess.prod_main_cont_exch(pc) 39 | main_insts = [] 40 | for inst in insts: 41 | pc = misc.inst2product(inst) 42 | mth = int(inst[-2:]) 43 | if mth in main_cont[pc]: 44 | main_insts.append(inst) 45 | return main_insts 46 | 47 | class MainApp(object): 48 | def __init__(self,name='SaveAgent', tday = datetime.date.today()): 49 | self.name = name 50 | app = self.app = tk.Tk() 51 | app.title("Save Data Tool") 52 | self.scroll_text = ScrolledText.ScrolledText(self.app, state='disabled') 53 | self.scroll_text.configure(font='TkFixedFont') 54 | # Create textLogger 55 | self.text_handler = TextHandler(self.scroll_text) 56 | self.scroll_text.pack() 57 | self.agent = None 58 | self.trader = None 59 | self.user = None 60 | self.scur_day = tday 61 | menu = tk.Menu(self.app) 62 | menu.add_command(label="Update contracts", command=self.onUpdateCont) 63 | menu.add_command(label="Restart agent", command=self.onRestart) 64 | menu.add_command(label="Exit", command=self.onExit) 65 | app.config(menu=menu) 66 | 67 | def onUpdateCont(self): 68 | t = threading.Thread(target=update_contract_table.main) 69 | t.start() 70 | 71 | def onRestart(self): 72 | if self.agent != None: 73 | self.scur_day = self.agent.scur_day 74 | save_insts = filter_main_cont(self.scur_day) 75 | self.agent = agent.SaveAgent(name = self.name, trader = None, cuser = None, instruments=save_insts, daily_data_days=0, min_data_days=0, tday = tday) 76 | self.agent.logger.addHandler(self.text_handler) 77 | fut_api.make_user(self.agent, misc.PROD_USER) 78 | return 79 | 80 | def onExit(self): 81 | if self.agent != None: 82 | self.agent.mdapis = [] 83 | self.agent.trader = None 84 | self.app.destroy() 85 | return 86 | 87 | def main(app_name, tday): 88 | logging.basicConfig(filename="save_all_agent.log",level=logging.INFO,format='%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s') 89 | m=MainApp(app_name, tday) 90 | m.app.mainloop() 91 | 92 | if __name__ == '__main__': 93 | args = sys.argv[1:] 94 | if len(args) < 2: 95 | tday = datetime.date.today() 96 | else: 97 | tday = datetime.datetime.strptime(args[1], '%Y%m%d').date() 98 | if len(args) < 1: 99 | app_name = 'SaveAgent' 100 | else: 101 | app_name = args[0] 102 | main(app_name, tday) -------------------------------------------------------------------------------- /sec_bits.py: -------------------------------------------------------------------------------- 1 | import platform 2 | from base import * 3 | 4 | datayes_token = 'xxxxx' 5 | 6 | dbconfig = {'user': 'xxxxx', 7 | 'password':'xxxxx', 8 | 'host':'localhost', 9 | 'database': 'xxxxx', 10 | } 11 | 12 | EMAIL_HOTMAIL = {'host': 'smtp.live.com', 13 | 'user': 'xxxxxx@hotmail.com', 14 | 'passwd': 'xxxxx'} 15 | 16 | 17 | def get_prod_folder(): 18 | folder = '' 19 | system = platform.system() 20 | if system == 'Linux': 21 | folder = '/home/xxx/' 22 | elif system == 'Windows': 23 | folder = 'C:\\xxx\\' 24 | return folder 25 | -------------------------------------------------------------------------------- /strat_dual_thrust.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | #from base import * 3 | from misc import * 4 | from strategy import * 5 | 6 | class DTTrader(Strategy): 7 | def __init__(self, name, underliers, volumes, agent = None, trade_unit = [], ratios = [], lookbacks=[], daily_close = False, email_notify = None, ma_win = 10, min_rng = [0.00]): 8 | Strategy.__init__(self, name, underliers, volumes, trade_unit, agent, email_notify) 9 | self.lookbacks = lookbacks 10 | numAssets = len(underliers) 11 | self.ratios = [[0.5, 0.5]] * numAssets 12 | if len(ratios) > 1: 13 | self.ratios = ratios 14 | elif len(ratios) == 1: 15 | self.ratios = ratios * numAssets 16 | if len(lookbacks) > 0: 17 | self.lookbacks = lookbacks 18 | else: 19 | self.lookbacks = [0] * numAssets 20 | self.cur_rng = [0.0] * numAssets 21 | self.cur_ma = [0.0] * numAssets 22 | self.tday_open = [0.0] * numAssets 23 | self.tick_base = [0.0] * numAssets 24 | self.order_type = OPT_LIMIT_ORDER 25 | self.daily_close_buffer = 3 26 | self.close_tday = [False] * numAssets 27 | if len(daily_close) > 1: 28 | self.close_tday = daily_close 29 | elif len(daily_close) == 1: 30 | self.close_tday = daily_close * numAssets 31 | self.ma_win = ma_win 32 | self.num_tick = 1 33 | self.min_rng = [0.0] * numAssets 34 | if len(min_rng) > 1: 35 | self.min_rng = min_rng 36 | elif len(min_rng) == 1: 37 | self.min_rng = min_rng * numAssets 38 | 39 | def initialize(self): 40 | self.load_state() 41 | for idx, underlier in enumerate(self.underliers): 42 | inst = underlier[0] 43 | self.tick_base[idx] = self.agent.instruments[inst].tick_base 44 | ddf = self.agent.day_data[inst] 45 | win = self.lookbacks[idx] 46 | if win > 0: 47 | self.cur_rng[idx] = max(max(ddf.ix[-win:,'high'])- min(ddf.ix[-win:,'close']), max(ddf.ix[-win:,'close']) - min(ddf.ix[-win:,'low'])) 48 | elif win == 0: 49 | self.cur_rng[idx] = max(max(ddf.ix[-2:,'high'])- min(ddf.ix[-2:,'close']), max(ddf.ix[-2:,'close']) - min(ddf.ix[-2:,'low'])) 50 | self.cur_rng[idx] = max(self.cur_rng[idx] * 0.5, ddf.ix[-1,'high']-ddf.ix[-1,'close'],ddf.ix[-1,'close']-ddf.ix[-1,'low']) 51 | else: 52 | self.cur_rng[idx] = max(ddf.ix[-1,'high']- ddf.ix[-1,'low'], abs(ddf.ix[-1,'close'] - ddf.ix[-2,'close'])) 53 | self.cur_ma[idx] = ddf.ix[-self.ma_win:, 'close'].mean() 54 | min_id = self.agent.instruments[inst].last_tick_id/1000 55 | min_id = int(min_id/100)*60 + min_id % 100 - self.daily_close_buffer 56 | self.last_min_id[idx] = int(min_id/60)*100 + min_id % 60 57 | self.save_state() 58 | return 59 | 60 | def save_local_variables(self, file_writer): 61 | for idx, underlier in enumerate(self.underliers): 62 | inst = underlier[0] 63 | row = ['CurrRange', str(inst), self.cur_rng[idx]] 64 | file_writer.writerow(row) 65 | return 66 | 67 | def load_local_variables(self, row): 68 | if row[0] == 'CurrRange': 69 | inst = str(row[1]) 70 | idx = self.under2idx[inst] 71 | if idx >= 0: 72 | self.cur_rng[idx] = float(row[2]) 73 | return 74 | 75 | def on_tick(self, idx, ctick): 76 | if len(self.submitted_trades[idx]) > 0: 77 | return 78 | inst = self.underliers[idx][0] 79 | self.tday_open[idx] = self.agent.cur_day[inst]['open'] 80 | if (self.tday_open[idx] <= 0.0) or (self.cur_rng[idx] <= 0) or (self.curr_prices[idx] <= 0.001): 81 | self.logger.warning("warning: open price =0.0 or range = 0.0 or curr_price=0 for inst=%s for stat = %s" % (inst, self.name)) 82 | return 83 | min_id = self.agent.tick_id/1000.0 84 | num_pos = len(self.positions[idx]) 85 | buysell = 0 86 | if num_pos > 1: 87 | self.logger.warning('something wrong with position management - submitted trade is empty but trade position is more than 1') 88 | return 89 | elif num_pos == 1: 90 | buysell = self.positions[idx][0].direction 91 | tick_base = self.tick_base[idx] 92 | t_open = self.tday_open[idx] 93 | c_rng = max(self.cur_rng[idx] * self.ratios[idx][0], t_open * self.min_rng[idx]) 94 | buy_trig = t_open + c_rng 95 | sell_trig = t_open - c_rng 96 | if self.cur_ma[idx] > t_open: 97 | buy_trig += self.ratios[idx][1] * c_rng 98 | elif self.cur_ma[idx] < t_open: 99 | sell_trig -= self.ratios[idx][1] * c_rng 100 | 101 | buy_trig = min(self.agent.instruments[inst].up_limit - 5*tick_base, buy_trig) 102 | sell_trig = max(self.agent.instruments[inst].down_limit + 5*tick_base, sell_trig) 103 | 104 | if (min_id >= self.last_min_id[idx]): 105 | if (buysell!=0) and (self.close_tday[idx]): 106 | msg = 'DT to close position before EOD for inst = %s, direction=%s, volume=%s, current tick_id = %s' \ 107 | % (inst, buysell, self.trade_unit[idx], min_id) 108 | self.close_tradepos(idx, self.positions[idx][0], self.curr_prices[idx] - buysell * self.num_tick * tick_base) 109 | self.status_notifier(msg) 110 | self.save_state() 111 | return 112 | 113 | if ((self.curr_prices[idx] >= buy_trig) and (buysell <=0)) or ((self.curr_prices[idx] <= sell_trig) and (buysell >=0)): 114 | if buysell!=0: 115 | msg = 'DT to close position for inst = %s, open= %s, buy_trig=%s, sell_trig=%s, curr_price= %s, direction=%s, volume=%s' \ 116 | % (inst, self.tday_open[idx], buy_trig, sell_trig, self.curr_prices[idx], buysell, self.trade_unit[idx]) 117 | self.close_tradepos(idx, self.positions[idx][0], self.curr_prices[idx] - buysell * self.num_tick * tick_base) 118 | self.status_notifier(msg) 119 | if self.trade_unit[idx] <= 0: 120 | return 121 | if (self.curr_prices[idx] >= buy_trig): 122 | buysell = 1 123 | else: 124 | buysell = -1 125 | msg = 'DT to open position for inst = %s, open= %s, buy_trig=%s, sell_trig=%s, curr_price= %s, direction=%s, volume=%s' \ 126 | % (inst, self.tday_open[idx], buy_trig, sell_trig, self.curr_prices[idx], buysell, self.trade_unit[idx]) 127 | self.open_tradepos(idx, buysell, self.curr_prices[idx] + buysell * self.num_tick * tick_base) 128 | self.status_notifier(msg) 129 | self.save_state() 130 | return 131 | 132 | def update_trade_unit(self): 133 | pass 134 | -------------------------------------------------------------------------------- /strats/60-The Volatility (Regime) Switch Indicator.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/60-The Volatility (Regime) Switch Indicator.pdf -------------------------------------------------------------------------------- /strats/Arma11.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/Arma11.pdf -------------------------------------------------------------------------------- /strats/Binary_if_3min.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/Binary_if_3min.txt -------------------------------------------------------------------------------- /strats/CU_5mins_UpperBand_LowerBand.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/CU_5mins_UpperBand_LowerBand.txt -------------------------------------------------------------------------------- /strats/EmpiricalModeDecomposition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/EmpiricalModeDecomposition.pdf -------------------------------------------------------------------------------- /strats/Exit Strategy ATR Ratchet.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/Exit Strategy ATR Ratchet.doc -------------------------------------------------------------------------------- /strats/IF_1min_MACD.txt: -------------------------------------------------------------------------------- 1 | DIFF:=EMA(CLOSE,12) - EMA(CLOSE,26); 2 | DEA:=EMA(DIFF,9); 3 | MACD:=2*(DIFF-DEA);//MACD 4 | F:=REF(AVPRICE,BARSBK); //调用买开那根K的线的均线价格 5 | G:=REF(AVPRICE,BARSSK); 6 | BK1:=MACD>REF(MACD,1) AND REF(MACD,1)>REF(MACD,2); 7 | BK2:=MACD<=-0.5 AND REF(MACD,2)<=LLV(MACD,10); 8 | BK1 AND BK2,BK; 9 | SP1:=L<=BKPRICE-5;//买开后,最低价低于买开价5个点以上止损 10 | SP2:=MACD>=0.5 AND REF(MACD,1)>=HHV(MACD,10) AND MACD<=REF(MACD,1); 11 | SP1 OR SP2,SP; 12 | SK1:=MACD=0.5 AND REF(MACD,2)>=HHV(MACD,10); 14 | SK1 AND SK2,SK; 15 | BP1:=C>=G+5; 16 | BP2:=MACD<=-0.5 AND REF(MACD,1)<=LLV(MACD,10) AND MACD>=REF(MACD,1); 17 | BP1 OR BP2,BP; 18 | AUTOFILTER; -------------------------------------------------------------------------------- /strats/IF_Range_Breakout_1mins.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/IF_Range_Breakout_1mins.txt -------------------------------------------------------------------------------- /strats/Kurtosis-Skewing交易策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TBKurtosis-Skewing交易策略 2 | 3 | 是一个基于数据分布的峰度(kurtosis)和偏度(skewness)的交易策略。当数据呈现趋势性,并且潜在趋势为正时,我们做多。当数据呈现趋势性,并且潜在趋势为负时,我们做空。当趋势发生反转后,我们平仓。那么,我们如何确定趋势和趋势的强度呢?让我们先来复习一下峰度和偏度的定义。 4 | 5 | 峰度(kurtosis),是描绘一组数据的分布形态的陡峭程度的统计量。正态分布的kurtosis为3,所以我们把kurtosis大于3的称作尖峰,表示数据的分布比正态分布更集中和陡峭。我们把kurtosis小于3的作为平峰型,表示数据分布比之正态分布更为平滑。峰度的计算公式可以在网上随意找到,MATLAB或R等统计学软件中也都有内部实现。这里我们所指代的分度是真实峰度减去3之后的值。在金融市场,峰度大于0表现为无趋势(sideway market),峰度小于0表现为趋势市(trending market)。 6 | 7 | 偏度(skewness)描绘的是数据分布的对称性,或者说是数据中众数(mode)的位置。skewness等于0刻画的是完美的对称性。这个统计量同样需要和正态分布比较:偏度大于0表明和正态分布相比,该数组呈现右偏,表现为右部的长尾并且极端值较多分布于右部;反之为左偏,表现为左部的长尾并且极端值较多分布于左部。在金融市场,偏度大于0可以解释为数据倾向于汇聚成向上的趋势,偏度小于0可以解释为数据倾向于汇聚成下降的趋势。 8 | 9 | 因此,我们得出以下的交易法则: 10 | 11 | 若采用趋势跟随型策略: 12 | 13 | 当峰度小于0(市场处于趋势市),偏度大于0(趋势为上升),波动性高于某一特定水平时,做多; 14 | 15 | 当峰度小于0(市场处于趋势市),偏度大于0(趋势为上升),波动性高于某一特定水平时,做空; 16 | 17 | 这里波动性可以用真实波动区间(ATR)来估算。表示为公式为: 18 | 19 | Buy when kurtosis(N1) crosses below 0, skew(N2) > 0, and ATR(N3) > minimum level. 20 | 21 | Sell when kurtosis(N1) crosses below 0, skew(N2) < 0, and ATR(N3) > minimum level. 22 | 23 | 24 | 25 | 若采用均值回归型策略: 26 | 27 | 当峰度大于0(市场处于mean-reversal),偏度小于0(价格偏向较低方向),波动性高于某一特定水平时,做多; 28 | 29 | 当峰度大于0(市场处于mean-reversal),偏度大于0(价格偏向较高方向),波动性高于某一特定水平时,做空; 30 | 31 | 这里波动性可以用真实波动区间(ATR)来估算。表示为公式为: 32 | 33 | Buy when kurtosis(N1) crosses up 0, skew(N2) < 0, and ATR(N3) > minimum level. 34 | 35 | Sell when kurtosis(N1) crosses up0, skew(N2) > 0, and ATR(N3) > minimum level. 36 | 37 | 38 | 对应的离场法则大家可以自己设定。比如说: 39 | 40 | 止损离场 41 | 42 | 固定持有周期 43 | 44 | 当峰度变化转向 45 | 46 | 当采用趋势跟踪型策略时,我们希望波动性不要过大。因此,我们在波动性大于某一特定值时离场。当采用均值回归时,我们希望波动性较大,因此,我们在波动性低于某值时离场。 -------------------------------------------------------------------------------- /strats/K线形态多空策略源码.txt: -------------------------------------------------------------------------------- 1 | 开拓者K线形态多空策略源码(用EMA过小震荡行情)[开拓者公式] 2 | 3 | 开多条件为:当前K线的收盘价比上根K线的收盘价高出N点,连续3次达到条件,则开多。开空反之。用EMA过滤。 4 | 5 | 6 | Params 7 | Numeric lots(1); 8 | Numeric p1(5); 9 | Numeric p2(5); 10 | Numeric Length(5); 11 | 12 | Vars 13 | BoolSeries Cha1; 14 | BoolSeries Cha2; 15 | NumericSeries Ema; 16 | 17 | Begin 18 | 19 | Cha1=Close[1]-Close[2]>P1*MinMove*PriceScale; 20 | 21 | Cha2=Close[2]-Close[1]>p2*MinMove*PriceScale; 22 | 23 | Ema=XAverage(XAverage(XAverage(XAverage(Close,Length),Length),Length),Length); 24 | 25 | If(Cha1 and Cha1[1] and Cha1[2] and Close[1]>Ema[1]) 26 | { 27 | Buy(lots,Open); 28 | } 29 | 30 | If(Cha2 and Cha2[1] and Cha2[2] and Close[1]0) counted_bars--; 74 | if(counted_bars==0) counted_bars++; 75 | if (BackPeriod==0) limit=Bars-counted_bars; else limit=BackPeriod; 76 | //---- fill in buffervalues 77 | InitDir = 0; 78 | for(int i=limit; i>=0; i--) 79 | { 80 | if (MedianPrice) PriceLvl = (High[i] + Low[i])/2; 81 | else PriceLvl = Close[i]; 82 | 83 | if (MedianBase) { 84 | PriceCurr = (High[i] + Low[i])/2; 85 | PricePrev = (High[i-1] + Low[i-1])/2; 86 | } 87 | else { 88 | PriceCurr = Close[i]; 89 | PricePrev = Close[i-1]; 90 | } 91 | 92 | if(InitDir == 0) { 93 | CurrUp=PriceCurr - (iATR(NULL,0,ATRPeriod,i) * Factor); 94 | PrevUp=PricePrev - (iATR(NULL,0,ATRPeriod,i-1) * Factor); 95 | CurrDn=PriceCurr + (iATR(NULL,0,ATRPeriod,i) * Factor); 96 | PrevDn=PricePrev + (iATR(NULL,0,ATRPeriod,i-1) * Factor); 97 | 98 | if (CurrUp > PrevUp) Dir = 1; 99 | LvlUp = CurrUp; 100 | if (CurrDn < PrevDn) Dir = -1; 101 | LvlDn = CurrDn; 102 | InitDir = 1; 103 | 104 | } 105 | 106 | CurrUp=PriceLvl - (iATR(NULL,0,ATRPeriod,i) * Factor); 107 | CurrDn=PriceLvl + (iATR(NULL,0,ATRPeriod,i) * Factor); 108 | 109 | //if (i==0) Comment("Dir:",Dir,",CurrUp:",CurrUp,",PrevUp:",PrevUp,",CurrDn:",CurrDn,",PrevDn:",PrevDn); 110 | if (Dir == 1) { 111 | if (CurrUp > LvlUp) { 112 | ind_buffer1[i] = CurrUp-distance; 113 | LvlUp = CurrUp; 114 | } 115 | else { 116 | ind_buffer1[i] = LvlUp-distance; 117 | } 118 | ind_buffer2[i] = EMPTY_VALUE; 119 | if (CloseBase) PriceHLorC = Close[i]; else PriceHLorC=Low[i]; 120 | if (PriceHLorC < ind_buffer1[i]) { 121 | Dir = -1; 122 | LvlDn = 1000; 123 | } 124 | } 125 | 126 | if (Dir == -1) { 127 | if (CurrDn < LvlDn) { 128 | ind_buffer2[i] = CurrDn+distance; 129 | LvlDn = CurrDn; 130 | } 131 | else { 132 | ind_buffer2[i] = LvlDn+distance; 133 | } 134 | ind_buffer1[i] = EMPTY_VALUE; 135 | if (CloseBase) PriceHLorC = Close[i]; else PriceHLorC=High[i]; 136 | if (PriceHLorC > ind_buffer2[i]) { 137 | Dir = 1; 138 | LvlUp = 0; 139 | } 140 | } 141 | 142 | if (Dir == 1) { 143 | if (CurrUp > LvlUp) { 144 | ind_buffer1[i] = CurrUp-distance; 145 | LvlUp = CurrUp; 146 | } 147 | else { 148 | ind_buffer1[i] = LvlUp-distance; 149 | } 150 | ind_buffer2[i] = EMPTY_VALUE; 151 | if (CloseBase) PriceHLorC = Close[i]; else PriceHLorC=Low[i]; 152 | if (PriceHLorC < ind_buffer1[i]) { 153 | Dir = -1; 154 | LvlDn = 1000; 155 | } 156 | } 157 | 158 | //if (ind_buffer1[0]!=EMPTY_VALUE && ind_buffer1[1]==EMPTY_VALUE) {ind_buffer1[i+1]=ind_buffer1[i];} 159 | //if (ind_buffer2[0]!=EMPTY_VALUE && ind_buffer2[1]==EMPTY_VALUE) {ind_buffer2[i+1]=ind_buffer2[i];} 160 | 161 | } 162 | 163 | 164 | //---- done 165 | return(0); 166 | } -------------------------------------------------------------------------------- /strats/asctrend systems/ATR_Stop.mq4: -------------------------------------------------------------------------------- 1 | //+------------------------------------------------------------------+ 2 | //| BAT ATR v2.mq4 | 3 | //+------------------------------------------------------------------+ 4 | #property copyright "Copyright Team Aphid" 5 | #property link "" 6 | //---- indicator settings 7 | #property indicator_chart_window 8 | #property indicator_buffers 3 9 | #property indicator_color1 RoyalBlue 10 | #property indicator_color2 RoyalBlue 11 | #property indicator_color3 255255255 12 | #property indicator_width3 1 13 | 14 | #define EMPV -1 15 | 16 | //---- indicator parameters 17 | extern int ATRPeriod = 10; 18 | extern double Factor = 2; 19 | extern bool MedianPrice = true; 20 | extern bool MedianBase = true; 21 | extern bool CloseBase = false; 22 | extern double distance = 0; 23 | 24 | //---- indicator buffers 25 | double up_line[]; 26 | double dn_line[]; 27 | double sig_dot[]; 28 | 29 | //+------------------------------------------------------------------+ 30 | //| Custom indicator initialization function | 31 | //+------------------------------------------------------------------+ 32 | int init() 33 | { 34 | //---- drawing settings 35 | SetIndexStyle(0,DRAW_LINE); 36 | SetIndexDrawBegin(0,ATRPeriod); 37 | SetIndexBuffer(0,up_line); 38 | SetIndexEmptyValue(0,EMPV); 39 | SetIndexStyle(1,DRAW_LINE); 40 | SetIndexDrawBegin(1,ATRPeriod); 41 | SetIndexBuffer(1,dn_line); 42 | SetIndexEmptyValue(1,EMPV); 43 | SetIndexStyle(2,DRAW_ARROW); 44 | SetIndexArrow(2,108); 45 | SetIndexDrawBegin(2,ATRPeriod); 46 | SetIndexBuffer(2,sig_dot); 47 | SetIndexEmptyValue(2,EMPV); 48 | 49 | IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2); 50 | //---- name for DataWindow and indicator subwindow label 51 | IndicatorShortName("BAT ATR("+ATRPeriod+" * "+Factor+")"); 52 | SetIndexLabel(0,"Support"); 53 | SetIndexLabel(1,"Resistance"); 54 | //---- initialization done 55 | return(0); 56 | } 57 | //+------------------------------------------------------------------+ 58 | //| Moving Averages Convergence/Divergence | 59 | //+------------------------------------------------------------------+ 60 | int start() 61 | { 62 | int counted_bars=IndicatorCounted(); 63 | int limit; 64 | static int dir=1; 65 | double PrevUp, PrevDn; 66 | double CurrUp, CurrDn; 67 | double PriceLvl; 68 | double PriceHLorC; 69 | static double LvlUp=0,LvlDn=100000; 70 | //---- check for possible errors 71 | if (counted_bars<0) return(-1); 72 | //---- last counted bar will be recounted 73 | if (counted_bars>=ATRPeriod) limit=Bars-counted_bars; 74 | else limit=Bars-ATRPeriod-1; 75 | if (limit<0) return (-1); 76 | //---- fill in buffervalues 77 | for(int i=limit; i>0; i--) { 78 | if (MedianPrice) PriceLvl = (High[i] + Low[i])/2; 79 | else PriceLvl = Close[i]; 80 | 81 | CurrUp=PriceLvl - (iATR(NULL,0,ATRPeriod,i) * Factor); 82 | CurrDn=PriceLvl + (iATR(NULL,0,ATRPeriod,i) * Factor); 83 | 84 | up_line[i]=EMPV; 85 | dn_line[i]=EMPV; 86 | sig_dot[i]=EMPV; 87 | 88 | if (dir>0) { 89 | if (CloseBase) PriceHLorC = Close[i]; else PriceHLorC=Low[i]; 90 | if (PriceHLorCLvlUp) LvlUp=CurrUp; 97 | up_line[i] = LvlUp-distance; 98 | } 99 | } else { 100 | if (CloseBase) PriceHLorC = Close[i]; else PriceHLorC=High[i]; 101 | if (PriceHLorC>LvlDn) { 102 | dir=1; 103 | LvlUp=CurrUp; 104 | up_line[i]=LvlUp-distance; 105 | sig_dot[i]=LvlUp-distance; 106 | } else { 107 | if (CurrDn0) { 116 | if (CloseBase) PriceHLorC = Close[0]; else PriceHLorC=Low[0]; 117 | if (PriceHLorCLvlUp) up_line[0] = CurrUp-distance; 122 | up_line[0] = LvlUp-distance; 123 | } 124 | } else { 125 | if (CloseBase) PriceHLorC = Close[0]; else PriceHLorC=High[0]; 126 | if (PriceHLorC>LvlDn) { 127 | up_line[0]=CurrUp-distance; 128 | sig_dot[0]=CurrUp-distance; 129 | } else { 130 | if (CurrDn0) counted_bars--; 47 | limit=Bars-counted_bars; 48 | //---- 49 | for(int i = 0 ;i < limit ;i++) 50 | { 51 | double f1u = iCustom(Symbol(),0,"Fisher_v1",10,4,0,0,i);//up 52 | double f2u = iCustom(Symbol(),0,"Fisher_v1",10,4,0,0,i+1);//up 53 | double f3u = iCustom(Symbol(),0,"Fisher_v1",10,4,0,0,i+2);//up 54 | 55 | double f1d = iCustom(Symbol(),0,"Fisher_v1",10,4,0,1,i);//dn 56 | double f2d = iCustom(Symbol(),0,"Fisher_v1",10,4,0,1,i+1);//dn 57 | double f3d = iCustom(Symbol(),0,"Fisher_v1",10,4,0,1,i+2);//dn 58 | 59 | if(f1u < f2u && f2u > f3u) 60 | { 61 | exitL[i] = Low[i]; 62 | exitS[i] = 0.0; 63 | } 64 | else if(f1d > f2d && f2d < f3d) 65 | { 66 | exitS[i] = High[i]; 67 | exitL[i] = 0.0; 68 | } 69 | } 70 | //---- 71 | return(0); 72 | } 73 | //+------------------------------------------------------------------+ -------------------------------------------------------------------------------- /strats/asctrend systems/Fisher_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/Fisher_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/LabTrend1_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/LabTrend1_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/LabTrend2_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/LabTrend2_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/LabTrend3_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/LabTrend3_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR Line.mql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/NRTR Line.mql -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR WATR.mql: -------------------------------------------------------------------------------- 1 | /*[[ 2 | Name := NRTR WATR 3 | Author := VG - many thanks to Konkop and dupidu 4 | Link := 4vg@mail.ru 5 | Separate Window := No 6 | First Color := Red 7 | First Draw Type := Symbol 8 | First Symbol := 119 9 | Use Second Data := Yes 10 | Second Color := LimeGreen 11 | Second Draw Type := Symbol 12 | Second Symbol := 119 13 | ]]*/ 14 | 15 | Input : AveragePeriod(10),Reg(1); 16 | 17 | Variable : bar(0); 18 | Variable : value(0); 19 | Variable : price(0); 20 | Variable : trend(0),dK(0), AvgRange(0),i(0),WATR(0),StartBars(0); 21 | 22 | SetLoopCount(0); 23 | 24 | AvgRange=0; 25 | for i=AveragePeriod DownTo 1 { 26 | dK = 1+(AveragePeriod-i)/AveragePeriod; 27 | AvgRange=AvgRange+ dK*Abs(High[i]-Low[i]); 28 | }; 29 | WATR = AvgRange/AveragePeriod; 30 | 31 | 32 | if Close[StartBars-1] > Open[StartBars-1] then { 33 | value = Close[StartBars - 1] * (1 - WATR); 34 | trend = 1; 35 | SetIndexValue2(StartBars - 1, value); 36 | }; 37 | 38 | if Close[StartBars-1] < Open[StartBars-1] then { 39 | value = Close[StartBars - 1] * (1 + WATR); 40 | trend = -1; 41 | SetIndexValue(StartBars - 1, value); 42 | }; 43 | 44 | for bar = Bars - AveragePeriod downto 0 { 45 | if Reg = 2 then { 46 | AvgRange=0; 47 | for i=1 To AveragePeriod { 48 | dK = 1+(AveragePeriod-i)/AveragePeriod; 49 | AvgRange=AvgRange+ dK*Abs(High[bar + i]-Low[bar + i]); 50 | }; 51 | WATR = AvgRange/AveragePeriod; 52 | }; 53 | if trend >= 0 then { 54 | if Close[bar] > price then price = Close[bar]; 55 | value = price * (1 - WATR); 56 | if Close[bar] < value then { 57 | price = Close[bar]; 58 | value = price * (1 + WATR); 59 | trend = -1; 60 | }; 61 | } 62 | else 63 | if trend <= 0 then { 64 | if Close[bar] < price then price = Close[bar]; 65 | value = price * (1 + WATR); 66 | if Close[bar] > value then { 67 | price = Close[bar]; 68 | value = price * (1 - WATR); 69 | trend = 1; 70 | }; 71 | }; 72 | 73 | if trend = -1 then SetIndexValue(bar, value); 74 | if trend = 1 then SetIndexValue2(bar, value); 75 | }; -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR.mql: -------------------------------------------------------------------------------- 1 | /*[[ 2 | Name := NRTR 3 | Author := VG many thanks to Konkop and dupidu 4 | Link := 4vg@mail.ru 5 | Separate Window := No 6 | First Color := Red 7 | First Draw Type := Symbol 8 | First Symbol := 160 9 | Use Second Data := Yes 10 | Second Color := LimeGreen 11 | Second Draw Type := Symbol 12 | Second Symbol := 160 13 | ]]*/ 14 | 15 | //----------------------------------------------------------------------- 16 | Input : AveragePeriod(10); 17 | //---------------------------------------------------------------------- 18 | Variable : bar(0); 19 | Variable : value(0); 20 | Variable : price(0); 21 | Variable : trend(0),dK(0), AvgRange(0),i(0); 22 | SetLoopCount(0); 23 | AvgRange=0; 24 | for i=1 To AveragePeriod { AvgRange+= Abs(High[i]-Low[i]); }; 25 | dK = AvgRange/AveragePeriod; 26 | 27 | if Close[Bars-1] > Open[Bars-1] then { 28 | value = Close[Bars - 1] * (1 - dK); 29 | trend = 1; 30 | SetIndexValue2(Bars - 1, value); 31 | }; 32 | if Close[Bars-1] < Open[Bars-1] then { 33 | value = Close[Bars - 1] * (1 + dK); 34 | trend = -1; 35 | SetIndexValue(Bars - 1, value); 36 | }; 37 | for bar = Bars - 2 downto 0 { 38 | if trend >= 0 then { 39 | if Close[bar] > price then price = Close[bar]; 40 | value = price * (1 - dK); 41 | if Close[bar] < value then { 42 | price = Close[bar]; 43 | value = price * (1 + dK); 44 | trend = -1; 45 | }; 46 | } 47 | else 48 | if trend <= 0 then { 49 | if Close[bar] < price then price = Close[bar]; 50 | value = price * (1 + dK); 51 | if Close[bar] > value then { 52 | price = Close[bar]; 53 | value = price * (1 - dK); 54 | trend = 1; 55 | }; 56 | }; 57 | if trend = -1 then SetIndexValue(bar, value); 58 | if trend = 1 then SetIndexValue2(bar, value); 59 | }; 60 | // ---------------------- -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR_ColorLine_my.mql: -------------------------------------------------------------------------------- 1 | /*[[ 2 | Name := NRTR_WATR 3 | Author := Namux 4 | Notes := Trend indicator based on break of the price channel from KonKop 5 | Separate Window := No 6 | First Color := White 7 | First Draw Type := Line 8 | First Symbol := 160 9 | Use Second Data := Yes 10 | Second Color := Yellow 11 | Second Draw Type := Line 12 | Second Symbol := 160 13 | ]]*/ 14 | 15 | Input : ATRPeriod( 14 ); 16 | Input : Coefficient( 4 ); 17 | 18 | Variable : StartBar( 1000 ); 19 | Variable : Shift( 0 ); 20 | Variable : TrendUP( true ); 21 | Variable : Extremum( 0 ); 22 | Variable : ChannelWidth( 0 ); 23 | Variable : TR( 0 ); 24 | Array : Values[ 100 ]( 0 ); 25 | Variable : Head( 0 ); 26 | Variable : ATR( 0 ); 27 | Variable : J( 0 ); 28 | Variable : Weight( 0 ); 29 | Variable : Curr( 0 ); 30 | 31 | SetLoopCount( 0 ); 32 | 33 | if close[ StartBar - 2 ] > close[ StartBar - 1 ] then 34 | TrendUP = true 35 | else 36 | TrendUP = false; 37 | 38 | Extremum = close[ StartBar - 2 ]; 39 | 40 | For Shift = StartBar - 3 Downto 0 Begin 41 | 42 | TR = High[ Shift ] - Low[ Shift ]; 43 | 44 | if ( abs( High[ Shift ] - Close[ Shift + 1 ]) > TR ) then TR = abs( High[ Shift ] - Close[ Shift + 1 ]); 45 | 46 | if ( abs( low[ Shift ] - Close[ Shift + 1 ]) > TR ) then TR = abs( low[ Shift ] - Close[ Shift + 1 ]); 47 | 48 | if Shift == StartBar - 3 then 49 | for J = 0 to ATRPeriod - 1 50 | { 51 | Values[ J ] = TR; 52 | }; 53 | 54 | Values[ Head ] = TR; 55 | 56 | ATR = 0; 57 | Weight = ATRPeriod; 58 | Curr = Head; 59 | 60 | for J = 0 to ATRPeriod - 1 61 | { 62 | Atr += Values[ Curr ] * Weight; 63 | 64 | Weight -= 1; 65 | 66 | Curr -= 1; 67 | 68 | if Curr = -1 then Curr = ATRPeriod - 1; 69 | } 70 | 71 | ATR = ( 2 * ATR ) / ( ATRPeriod * ( ATRPeriod + 1 )); 72 | 73 | Head += 1; 74 | 75 | if Head = ATRPeriod then Head = 0; 76 | 77 | ChannelWidth = Coefficient * ATR; 78 | 79 | if TrendUP and ( low[ Shift ] < ( Extremum - ChannelWidth )) then begin 80 | TrendUP = false; 81 | Extremum = high[ Shift ]; 82 | end; 83 | 84 | if ( not TrendUP ) and ( high[ Shift ] > ( Extremum + ChannelWidth )) then begin 85 | TrendUP = true; 86 | Extremum = low[ Shift ]; 87 | End; 88 | 89 | if TrendUP and ( low[ Shift ] > Extremum ) then Extremum = low[ Shift ]; 90 | if ( not TrendUP ) and ( high[ Shift ] < Extremum ) then Extremum = high[ Shift ]; 91 | 92 | if TrendUP then 93 | { 94 | SetIndexValue( Shift, Extremum - ChannelWidth ); 95 | SetIndexValue2( Shift, -1 ); 96 | } 97 | else 98 | { 99 | SetIndexValue2( Shift, Extremum + ChannelWidth ); 100 | SetIndexValue( Shift, -1 ); 101 | }; 102 | 103 | End; 104 | 105 | -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR_Line1_separate.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/NRTR_Line1_separate.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/NRTR_dots1_separate.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/NRTR_dots1_separate.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/PriceChannel_Stop_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/PriceChannel_Stop_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/RSIFilter_v1.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/RSIFilter_v1.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/RoundPriceNE_big_separate.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/RoundPriceNE_big_separate.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/RoundPriceNE_pips.mq4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/RoundPriceNE_pips.mq4 -------------------------------------------------------------------------------- /strats/asctrend systems/TrendStrength_v2.mq5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/asctrend systems/TrendStrength_v2.mq5 -------------------------------------------------------------------------------- /strats/asctrend systems/WPRfast.mql: -------------------------------------------------------------------------------- 1 | /*[[ 2 | Name := WPRfast 3 | Author := OlegVS 4 | Link := http://www.company.com/ 5 | Separate Window := Yes 6 | First Color := Blue 7 | First Draw Type := Histogram 8 | First Symbol := 217 9 | Use Second Data := Yes 10 | Second Color := Red 11 | Second Draw Type := Histogram 12 | Second Symbol := 218 13 | Minimum Chart Limits := -1.000000 14 | Maximum Chart Limits := 1.000000 15 | ]]*/ 16 | inputs :P(9),n1(9),n2(49); 17 | 18 | Variable : shift(0); 19 | Variable : V1(0); 20 | Variable : V2(0); 21 | 22 | 23 | SetLoopCount(0); 24 | // loop from first bar to current bar (with shift=0) 25 | For shift = Bars-1 Downto 0 Begin 26 | V1=iWPR(P,shift)*iWPR(P,shift)/100; 27 | V2=Ceil(V1); 28 | If V2n2 then 31 | SetIndexValue2(shift, -(V2)); 32 | 33 | End; 34 | 35 | -------------------------------------------------------------------------------- /strats/asctrend systems/WPRslow.mql: -------------------------------------------------------------------------------- 1 | /*[[ 2 | Name := WPRslow 3 | Author := OlegVS 4 | Link := http://www.company.com/ 5 | Separate Window := Yes 6 | First Color := Blue 7 | First Draw Type := Histogram 8 | First Symbol := 217 9 | Use Second Data := Yes 10 | Second Color := Red 11 | Second Draw Type := Histogram 12 | Second Symbol := 218 13 | Minimum Chart Limits := -1.000000 14 | Maximum Chart Limits := 1.000000 15 | ]]*/ 16 | inputs :P(54),n1(9),n2(49); 17 | 18 | Variable : shift(0); 19 | Variable : V1(0); 20 | Variable : V2(0); 21 | 22 | 23 | SetLoopCount(0); 24 | // loop from first bar to current bar (with shift=0) 25 | For shift = Bars-1 Downto 0 Begin 26 | V1=iWPR(P,shift)*iWPR(P,shift)/100; 27 | V2=Ceil(V1); 28 | If V2n2 then 31 | SetIndexValue2(shift, -(V2)); 32 | 33 | End; 34 | 35 | -------------------------------------------------------------------------------- /strats/asctrend systems/iTrend_hist.mq4: -------------------------------------------------------------------------------- 1 | //+------------------------------------------------------------------+ 2 | //| iTrend_hist.mq4 | 3 | //| tonyc2a@yahoo.com | 4 | //| | 5 | //+------------------------------------------------------------------+ 6 | #property copyright "tonyc2a@yahoo.com" 7 | #property link "" 8 | #property indicator_separate_window 9 | #property indicator_buffers 2 10 | #property indicator_color1 Blue 11 | #property indicator_color2 Red 12 | #property indicator_minimum -1 13 | #property indicator_maximum 1 14 | 15 | 16 | //---- input parameters 17 | extern double iBandsDeviation=2; 18 | extern int iBandsMode0_2=0; // 0-2: MODE_MAIN, MODE_LOW, MODE_HIGH 19 | extern int iBandsPrice0_6=0; // 0-6: PRICE_CLOSE,PRICE_OPEN,PRICE_HIGH,PRICE_LOW,PRICE_MEDIAN,PRICE_TYPICAL,PRICE_WEIGHTED 20 | extern int iBandsPeriod=20; // 20 21 | extern int iPowerPrice0_6=0; // 0-6: PRICE_CLOSE,PRICE_OPEN,PRICE_HIGH,PRICE_LOW,PRICE_MEDIAN,PRICE_TYPICAL,PRICE_WEIGHTED 22 | extern int iPowerPeriod=13; // 13 23 | extern int iPriceType0_3=0; // 0-3: PRICE_CLOSE,PRICE_OPEN,PRICE_HIGH,PRICE_LOW 24 | 25 | //---- buffers 26 | double ExtMapBuffer1[]; 27 | double ExtMapBuffer2[]; 28 | 29 | //+------------------------------------------------------------------+ 30 | //| Custom indicator initialization function | 31 | //+------------------------------------------------------------------+ 32 | int init() 33 | { 34 | //---- indicators 35 | IndicatorBuffers(2); 36 | SetIndexStyle(0,DRAW_HISTOGRAM); 37 | SetIndexBuffer(0,ExtMapBuffer1); 38 | SetIndexLabel(0,"Blue"); 39 | SetIndexStyle(1,DRAW_HISTOGRAM); 40 | SetIndexBuffer(1,ExtMapBuffer2); 41 | SetIndexLabel(1,"Red"); 42 | //---- 43 | IndicatorShortName("iTrend"); 44 | //---- 45 | return(0); 46 | } 47 | //+------------------------------------------------------------------+ 48 | //| Custor indicator deinitialization function | 49 | //+------------------------------------------------------------------+ 50 | int deinit() 51 | { 52 | //---- TODO: add your code here 53 | //---- 54 | return(0); 55 | } 56 | //+------------------------------------------------------------------+ 57 | //| Custom indicator iteration function | 58 | //+------------------------------------------------------------------+ 59 | int start() 60 | { 61 | int counted_bars=IndicatorCounted(); 62 | //---- TODO: add your code here 63 | 64 | //+----Processes user parameters-------------------------------------+ 65 | double BandsMode,BandsPrice,PowerPrice; 66 | 67 | switch(iBandsMode0_2){ 68 | case 1: BandsMode=MODE_LOWER; 69 | case 2: BandsMode=MODE_UPPER; 70 | default: BandsMode=MODE_MAIN; 71 | } //end switch 72 | 73 | switch(iBandsPrice0_6){ 74 | case 1: BandsPrice=PRICE_OPEN; 75 | case 2: BandsPrice=PRICE_HIGH; 76 | case 3: BandsPrice=PRICE_LOW; 77 | case 4: BandsPrice=PRICE_MEDIAN; 78 | case 5: BandsPrice=PRICE_TYPICAL; 79 | case 6: BandsPrice=PRICE_WEIGHTED; 80 | default: BandsPrice=PRICE_CLOSE; 81 | } //end switch 82 | 83 | switch(iPowerPrice0_6){ 84 | case 1: PowerPrice=PRICE_OPEN; 85 | case 2: PowerPrice=PRICE_HIGH; 86 | case 3: PowerPrice=PRICE_LOW; 87 | case 4: PowerPrice=PRICE_MEDIAN; 88 | case 5: PowerPrice=PRICE_TYPICAL; 89 | case 6: PowerPrice=PRICE_WEIGHTED; 90 | default: PowerPrice=PRICE_CLOSE; 91 | } //end switch 92 | //+------------------------------------------------------------------+ 93 | 94 | //+----Main Section--------------------------------------------------+ 95 | double CurrentPrice, value1, value2, x, y; 96 | 97 | for(int i=0;i<=Bars;i++){ 98 | switch(iPriceType0_3){ 99 | case 1: CurrentPrice=Open[i]; 100 | case 2: CurrentPrice=High[i]; 101 | case 3: CurrentPrice=Low[i]; 102 | default: CurrentPrice=Close[i]; 103 | } //end switch 104 | 105 | x=CurrentPrice-iBands(Symbol(),Period(),iBandsPeriod,iBandsDeviation,0,BandsPrice,BandsMode,i); 106 | y=-(iBullsPower(Symbol(),Period(),iPowerPeriod,PowerPrice,i) + iBearsPower(Symbol(),Period(),iPowerPeriod,PowerPrice,i)); 107 | 108 | if(x<0) value1=0; 109 | if(x>0) value1=1; 110 | if(y<0) value2=0; 111 | if(y>0) value2=-1; 112 | 113 | ExtMapBuffer1[i]=value1; 114 | ExtMapBuffer2[i]=value2; 115 | } //end for 116 | //+------------------------------------------------------------------+ 117 | 118 | //ObjectCreate("vl",OBJ_VLINE,WindowFind("iTrend"),Time[-1],Close[0]); 119 | 120 | //---- 121 | return(0); 122 | } 123 | //+------------------------------------------------------------------+ -------------------------------------------------------------------------------- /strats/if_1mins_atr.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_1mins_atr.txt -------------------------------------------------------------------------------- /strats/if_3mins_cs.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_3mins_cs.txt -------------------------------------------------------------------------------- /strats/if_5_mins_yellow_qs.txt: -------------------------------------------------------------------------------- 1 | Params 2 | Numeric M(5); 3 | Numeric N(0.35); 4 | 5 | Vars 6 | Numeric TODAYBARS; 7 | Numeric SUMCLOSE; 8 | Numeric TRENDRATE; 9 | Numeric I; 10 | 11 | Begin 12 | 13 | TODAYBARS=BarsSinceToday; 14 | 15 | For I=1 TO M 16 | { 17 | SUMCLOSE=SUMCLOSE+Abs(C[i]-C[i+1]); 18 | } 19 | 20 | TRENDRATE=Average((C[1]-C[M])/SUMCLOSE,M); 21 | 22 | If(TODAYBARS>M && Time<0.1450) 23 | { 24 | If(TRENDRATE>2*N && MarketPosition==0) Buy(1,open); 25 | If(TRENDRATE<-2*N && MarketPosition==0) SellShort(1,open); 26 | } 27 | 28 | If(TODAYBARS>M && Time<0.1510) 29 | { 30 | If(TRENDRATE<-1*N) Sell(1,open); 31 | If(TRENDRATE>1*N) BuyToCover(1,open); 32 | } 33 | 34 | If(Time>=0.1510 && MarketPosition!=0) 35 | { 36 | Sell(1,O); 37 | BuyToCover(1,O); 38 | } 39 | 40 | PlotNumeric("1",TRENDRATE); 41 | 42 | End -------------------------------------------------------------------------------- /strats/if_5mins_bollzd.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Params 4 | Numeric ddan(0); 5 | Numeric Lots(1); 6 | Numeric beilv(2.05); 7 | Numeric tten(15); 8 | Numeric tt1(9.30); 9 | Numeric tt2(14.50); 10 | 11 | Numeric bdd(1.88); 12 | Numeric uu1(26); 13 | Numeric vv1(18); 14 | Numeric ww1(4); 15 | Numeric yy1(3); 16 | Numeric xx1(14); 17 | 18 | 19 | Numeric zhiyy(16); 20 | 21 | Vars 22 | 23 | NumericSeries jixian; 24 | NumericSeries toop; 25 | NumericSeries boop; 26 | 27 | 28 | Numeric daizhua; 29 | 30 | NumericSeries iiii; 31 | NumericSeries hhhh; 32 | NumericSeries jjjj; 33 | NumericSeries kkkk; 34 | 35 | 36 | Begin 37 | hhhh=AverageFC(Close[1],xx1); 38 | iiii=AverageFC(Close[1],yy1); 39 | jjjj=AverageFC(Close[1],ww1); 40 | kkkk=AverageFC(Close[1],vv1); 41 | 42 | jixian = AverageFC(Close[1],uu1); 43 | daizhua = StandardDev(Close[1],uu1,2); 44 | toop = jixian + beilv * daizhua; 45 | boop = jixian - beilv * daizhua; 46 | 47 | 48 | If(Time==tten/100 and MarketPosition<>0) 49 | { If (MarketPosition==-1) 50 | {BuyToCover(abs(CurrentContracts),Open+ddan*MinMove()*PriceScale()); 51 | } 52 | If (MarketPosition==1) 53 | {Sell(abs(CurrentContracts),Open-ddan*MinMove()*PriceScale()); 54 | 55 | } 56 | Return; 57 | } 58 | 59 | 60 | If(Time>=tt1/100) 61 | { 62 | 63 | If(MarketPosition==0 and daizhua>=bdd and Time<=tt2/100) 64 | { 65 | if(High[1]>toop) 66 | { 67 | SellShort(lots,open-ddan*MinMove()*PriceScale()); 68 | 69 | Return; 70 | } 71 | 72 | If(Low[1]1) 84 | { 85 | 86 | 87 | 88 | If(CrossUnder(jjjj,kkkk) or Close[1]AvgEntryPrice) 110 | { 111 | Sell(abs(CurrentContracts),Open-ddan*MinMove()*PriceScale()); 112 | 113 | } 114 | Return; 115 | } 116 | } 117 | If(MarketPosition==-1 and BarsSinceLastEntry>1) 118 | { 119 | 120 | 121 | 122 | If(CrossOver(jjjj,kkkk) or close[1]>AvgEntryPrice+zhiyy) 123 | { 124 | BuyToCover(abs(CurrentContracts),Open+ddan*MinMove()*PriceScale()); 125 | 126 | 127 | 128 | 129 | 130 | If(Time<=tt2/100 ) 131 | { 132 | Buy(lots,Open+ddan*MinMove()*PriceScale()); 133 | 134 | 135 | } 136 | 137 | return; 138 | } 139 | 140 | 141 | 142 | 143 | If(CrossOver(iiii,hhhh)) 144 | { 145 | If(close[1]n10&&BarsSinceEntry>t1&&high>high[1]) 18 | { 19 | 20 | SellShort(0,Lowest(low[1],t1)+n10); 21 | 22 | } 23 | 24 | else If(MarketPosition == -1 && Highest(high[1],t1)-low>n10&&BarsSinceEntry>t1&&lowperiod&& Time<0.1450) 38 | { 39 | If(Efratio>2*N && MarketPosition==0) Buy(1,O); 40 | If(Efratio<-2*N && MarketPosition==0) SellShort(1,O); 41 | } 42 | 43 | If(mypra>period && Time<0.1510) 44 | { 45 | If(Efratio<-1*N) Sell(1,O); 46 | If(Efratio>1*N) BuyToCover(1,O); 47 | } 48 | 49 | If(Time>=0.1510 && MarketPosition!=0) 50 | { 51 | Sell(1,O); 52 | BuyToCover(1,O); 53 | } 54 | 55 | End 56 | 57 | -------------------------------------------------------------------------------- /strats/if_5mins_td.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_5mins_td.txt -------------------------------------------------------------------------------- /strats/if_5mins布林带策略.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_5mins布林带策略.txt -------------------------------------------------------------------------------- /strats/if_5mins高低点突破策略.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_5mins高低点突破策略.txt -------------------------------------------------------------------------------- /strats/if_5mis日内高低突破策略.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/if_5mis日内高低突破策略.txt -------------------------------------------------------------------------------- /strats/pta_30_uplowbas.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/pta_30_uplowbas.txt -------------------------------------------------------------------------------- /strats/pta_30mins_bdking.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/pta_30mins_bdking.txt -------------------------------------------------------------------------------- /strats/rb_5mins_breakout.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/rb_5mins_breakout.txt -------------------------------------------------------------------------------- /strats/rb_60_tp.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/rb_60_tp.txt -------------------------------------------------------------------------------- /strats/research reports/20150813-广发证券-另类交易策略之二十八:论RSI指标在股指期货日内交易中的使用.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/20150813-广发证券-另类交易策略之二十八:论RSI指标在股指期货日内交易中的使用.pdf -------------------------------------------------------------------------------- /strats/research reports/20170104-东方证券-《衍生品研究系列之四》:基于单特征因子的隐马尔科夫模型在商品期货上的应用.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/20170104-东方证券-《衍生品研究系列之四》:基于单特征因子的隐马尔科夫模型在商品期货上的应用.pdf -------------------------------------------------------------------------------- /strats/research reports/20170314-广发证券-交易性择时策略研究之九:利用均线间距变化提前预判趋势.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/20170314-广发证券-交易性择时策略研究之九:利用均线间距变化提前预判趋势.pdf -------------------------------------------------------------------------------- /strats/research reports/20180810-东方证券-东方证券衍生品系列研究之(十一):商品基本面量化研究之铁矿石.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/20180810-东方证券-东方证券衍生品系列研究之(十一):商品基本面量化研究之铁矿石.pdf -------------------------------------------------------------------------------- /strats/research reports/20181101-海通证券-海通证券金融工程专题报告:高频量价因子在股票与期货中的表现.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/20181101-海通证券-海通证券金融工程专题报告:高频量价因子在股票与期货中的表现.pdf -------------------------------------------------------------------------------- /strats/research reports/中信建投_20160118_大宗商品价格波动四周期嵌套模型的构建:大宗商品周期研究.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/中信建投_20160118_大宗商品价格波动四周期嵌套模型的构建:大宗商品周期研究.pdf -------------------------------------------------------------------------------- /strats/research reports/华泰期货_20170825_华泰期货量化专题报告:贝叶斯线性回归在期货交易中的应用.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/华泰期货_20170825_华泰期货量化专题报告:贝叶斯线性回归在期货交易中的应用.pdf -------------------------------------------------------------------------------- /strats/research reports/华泰期货_20171124_华泰期货量化策略专题报告:CTA量化策略因子系列(四)策略因子组合与择时.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/华泰期货_20171124_华泰期货量化策略专题报告:CTA量化策略因子系列(四)策略因子组合与择时.pdf -------------------------------------------------------------------------------- /strats/research reports/华泰证券_20130123_股指期货程序化交易研究之九:Pivot+Point策略.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/华泰证券_20130123_股指期货程序化交易研究之九:Pivot+Point策略.pdf -------------------------------------------------------------------------------- /strats/research reports/商品期货CTA专题报告(三):策略的趋势过滤-20170321-天风证券-14页.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/商品期货CTA专题报告(三):策略的趋势过滤-20170321-天风证券-14页.pdf -------------------------------------------------------------------------------- /strats/research reports/商品期货CTA专题报告(四):库存基本面与动量技术面共振的投资策略-20180105-天风证券-26页.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/商品期货CTA专题报告(四):库存基本面与动量技术面共振的投资策略-20180105-天风证券-26页.pdf -------------------------------------------------------------------------------- /strats/research reports/天风证券_20170914_天风证券金融工程:利用组合优化构建投资组合.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/天风证券_20170914_天风证券金融工程:利用组合优化构建投资组合.pdf -------------------------------------------------------------------------------- /strats/research reports/天风证券_20170921_天风证券金工专题报告:基于动态风险控制的组合优化模型.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/天风证券_20170921_天风证券金工专题报告:基于动态风险控制的组合优化模型.pdf -------------------------------------------------------------------------------- /strats/research reports/广发证券_20160318_广发证券FICC业务系列报告之三:商品期货跨市场套利解决方案.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/广发证券_20160318_广发证券FICC业务系列报告之三:商品期货跨市场套利解决方案.pdf -------------------------------------------------------------------------------- /strats/research reports/广发证券_20160601_精益求精:基于动量反转敏感度系数筛选的优化策略.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/广发证券_20160601_精益求精:基于动量反转敏感度系数筛选的优化策略.pptx -------------------------------------------------------------------------------- /strats/research reports/方正证券_20170918_方正证券CTA专题研究:基于平稳过程的CTA策略增强框架.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/方正证券_20170918_方正证券CTA专题研究:基于平稳过程的CTA策略增强框架.pdf -------------------------------------------------------------------------------- /strats/research reports/申万宏源_20170607_申万宏源趋势因子:动量与反转效应的结合.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/申万宏源_20170607_申万宏源趋势因子:动量与反转效应的结合.pdf -------------------------------------------------------------------------------- /strats/research reports/银河证券_20160317_银河证券β趋势控制策略(二):大宗商品的投资方式.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/银河证券_20160317_银河证券β趋势控制策略(二):大宗商品的投资方式.pdf -------------------------------------------------------------------------------- /strats/research reports/银河证券_20160412_β趋势控制策略(三):拐点的仓位控制.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/银河证券_20160412_β趋势控制策略(三):拐点的仓位控制.pdf -------------------------------------------------------------------------------- /strats/research reports/银河证券_20160706_金融工程-衍生品投机:β趋势控制策略(四)_提取震荡行情的回报.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/银河证券_20160706_金融工程-衍生品投机:β趋势控制策略(四)_提取震荡行情的回报.pdf -------------------------------------------------------------------------------- /strats/research reports/银河证券_20160831_金融工程-衍生品投机:β趋势控制策略(五)_震荡策略的设计与因子分析.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/research reports/银河证券_20160831_金融工程-衍生品投机:β趋势控制策略(五)_震荡策略的设计与因子分析.pdf -------------------------------------------------------------------------------- /strats/ru_15mins.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/ru_15mins.txt -------------------------------------------------------------------------------- /strats/sr_5mins_hl_atr.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Params 4 | Numeric ATRGET(0.61); 5 | 6 | Vars 7 | Numeric DayStart; 8 | Numeric PP; 9 | Numeric UP; 10 | Numeric DOWN; 11 | Numeric MyPrice; 12 | 13 | Begin 14 | DayStart = OpenD(0); 15 | PP = HighD(1) - LowD(1); 16 | UP = DayStart + PP * ATRGET; 17 | DOWN = DayStart - PP * ATRGET; 18 | 19 | If(MarketPosition <> 1 && High >= UP) 20 | { 21 | MyPrice = UP; 22 | If(Open > MyPrice) 23 | { 24 | MyPrice = Open; 25 | } 26 | Buy(1,MyPrice); 27 | Return; 28 | } 29 | 30 | If(MarketPosition <> -1 && Low <= DOWN) 31 | { 32 | MyPrice = DOWN; 33 | If(Open < MyPrice) 34 | { 35 | MyPrice = Open; 36 | } 37 | SellShort(1,MyPrice); 38 | Return; 39 | } 40 | 41 | End 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /strats/ssto交易系统策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB ssto 交易系统策略源码 2 | 3 | //------------------------------------------------------------------------ 4 | // 简称: ssto 5 | // 名称: 6 | // 类别: 公式应用 7 | // 类型: 用户应用 8 | // 输出: 9 | //------------------------------------------------------------------------ 10 | Params 11 | Numeric Length(20); //N 12 | Numeric SlowLength(24); //M1 13 | Numeric SmoothLength(10); //M2 14 | Numeric LongLength(20); 15 | Numeric lots(1); 16 | Numeric offset(0); 17 | Numeric stoploss(50); 18 | 19 | Vars 20 | NumericSeries HighestValue; 21 | NumericSeries LowestValue; 22 | NumericSeries RSV; 23 | NumericSeries FASTK; 24 | NumericSeries K1; 25 | NumericSeries D1; 26 | Numeric i_offset; 27 | Numeric BuyPosition; 28 | Numeric SellPosition; 29 | Numeric myEntryPrice; 30 | Numeric myExitPrice; 31 | 32 | Begin 33 | HighestValue = HighestFC(High, Length); 34 | LowestValue = LowestFC(Low, Length); 35 | RSV = (Close-LowestValue)/(HighestValue-LowestValue)*100; 36 | FASTK = SMA(RSV,SlowLength,1); 37 | K1 = SMA(FASTK,SmoothLength,1); 38 | D1 = SMA(K1,LongLength,1); 39 | i_offset = offset*MinMove*PriceScale; 40 | 41 | 42 | if(MarketPosition == 0) 43 | { 44 | if(CrossOver(K1,D1)) 45 | { 46 | buy(lots,Close[1]); 47 | Return; 48 | } 49 | //if(CrossUnder(K1,D1))//开空头 50 | //{ 51 | // SellShort(lots,Close[1]); 52 | // Return; 53 | //} 54 | } 55 | if(MarketPosition == 1)//平多 56 | { 57 | if(CrossUnder(K1,D1)) 58 | { 59 | Sell(lots,Close); 60 | Return; 61 | } 62 | } 63 | 64 | //止损 65 | If(MarketPosition == 1) 66 | { 67 | If(Low < EntryPrice - StopLoss * MinMove*PriceScale) 68 | { 69 | myExitPrice = EntryPrice - (StopLoss+1) * MinMove*PriceScale; 70 | myExitPrice = max(low,myExitPrice); 71 | Sell(lots,myExitPrice); 72 | } 73 | } 74 | Else If(MarketPosition == -1) 75 | { 76 | If(High > EntryPrice + StopLoss * MinMove*PriceScale) 77 | { 78 | myExitPrice = EntryPrice + (StopLoss+1) * MinMove*PriceScale; 79 | myExitPrice = min(high,myExitPrice); 80 | BuyToCover(lots,myExitPrice); 81 | } 82 | } 83 | end -------------------------------------------------------------------------------- /strats/thermostat系统源码.txt: -------------------------------------------------------------------------------- 1 | 开拓者thermostat系统源码[开拓者公式] 2 | 3 | 源码内容: 4 | 5 | inputs: 6 | bollingerlengths(50), 7 | trendliqlength(50), 8 | numstddevs(2), 9 | swingprcnt1(0.50), 10 | swingprcnt2(0.75), 11 | atrlength(10), 12 | swingtrendswitch(20); 13 | vars: 14 | cmival(0), 15 | buyeasierday(0), 16 | selleasierday(0), 17 | trendlokbuy(0), 18 | trendloksell(0), 19 | keyofday(0), 20 | swingbuypt(0), 21 | swingsellpt(0), 22 | trendbuypt(0), 23 | trendsellpt(0), 24 | swingprotstop(0); 25 | 26 | cmival=choppymarketindex(30); 27 | buyeasierday=0; 28 | selleasierday=0; 29 | 30 | trendlokbuy=average(low,3); 31 | trendloksell=average(high,3); 32 | 33 | keyofday=(high+low+close)/3; 34 | if(close>keyofday) then selleasierday=1; 35 | if(close<=keyofday) then buyeasierday=1; 36 | 37 | if(buyeasierday=1) then 38 | begin 39 | swingbuypt=open of tomorrow + swingprcnt1*avgtruerange(atrlength); 40 | swingsellpt=open of tomorrow - swingprcnt2*avgtruerange(atrlength); 41 | end; 42 | if(selleasierday=1) then 43 | begin 44 | swingbuypt=open of tomorrow + swingprcnt2*avgtruerange(atrlength); 45 | swingsellpt=open of tomorrow - swingprcnt1*avgtruerange(atrlength); 46 | end; 47 | 48 | swingbuypt=maxlist(swingbuypt,trendlokbuy); 49 | swingsellpt=minlist(swingsellpt,trendloksell); 50 | 51 | trendbuypt=bollingerband(close,bollingerlengths,numstddevs); 52 | trendsellpt=bollingerband(close,bollingerlengths,-numstddevs); 53 | 54 | if(cmival1) then buy("swingbuy") next bar at swingbuypt 57 | stop; 58 | if(marketposition<>-1) then sellshort("swingsell") next bar at 59 | swingsellpt stop; 60 | end 61 | else 62 | begin 63 | swingprotstop=3*avgtruerange(atrlength); 64 | buy("trendbuy") next bar at trendbuypt stop; 65 | sellshort("trendsell") next bar at trendsellpt stop; 66 | sell from entry("trendbuy") next bar at average(close,trendliqlenth) 67 | stop; 68 | buytocover from entry("trendsell") next bar at 69 | average(close,trendliqlength) stop; 70 | sell from entry("swingbuy") next bar at entryprice - swingprotstop 71 | stop; 72 | buytocover from entry("swingsell") next bar at entryprice + 73 | swingprotstop stop; 74 | end; -------------------------------------------------------------------------------- /strats/turtle_soup_source.txt: -------------------------------------------------------------------------------- 1 | INPUT: LENGTH(20),PREV(4),ENTRYADD(10 POINTS); 2 | 3 | VAR:HH(0),LL(0),NEWH(999),NEWL(999),Z(0),LEN(0),CD AYS(0),MP(0), 4 | TSSELL(0),TSBUY(99999),LGO(FALSE),SGO(FALSE), 5 | REBUY(99999),REBUYLIFE(0),RESELL(0),RESELLLIFE(0); 6 | ARRAY:HI[40](0),LO[40](99999); 7 | 8 | MP=MARKETPOSITION; 9 | 10 | IF DATACOMPRESSION=1 THEN BEGIN 11 | 12 | IF CURRENTBAR=1 THEN BEGIN 13 | LEN=MINLIST(LENGTH,39); 14 | IF LEN<1 THEN LEN=1; 15 | END; 16 | if D>D[1] then begin 17 | for value1=LEN downto 1 begin 18 | HI[value1]=HI[value1-1]; 19 | LO[value1]=LO[value1-1]; 20 | end; 21 | end; 22 | HI[0]=idhigh; 23 | LO[0]=idlow; 24 | IF D>D[1] THEN BEGIN 25 | CDAYS=CDAYS+1; 26 | NEWH=NEWH+1; 27 | NEWL=NEWL+1; 28 | LGO=TRUE; 29 | SGO=TRUE; 30 | REBUYLIFE=REBUYLIFE-1; 31 | RESELLLIFE=RESELLLIFE-1; 32 | HH=HI[LEN];LL=LO[LEN]; 33 | FOR Z=1 TO LEN-1 BEGIN 34 | IF HI[Z]>HH THEN HH=HI[Z]; 35 | IF LO[Z] END; 36 | IF HI[1]=HH THEN NEWH=1; 37 | IF LO[1]=LL THEN NEWL=1; 38 | END; 39 | 40 | IF H>=TSBUY[1] THEN BEGIN 41 | TSBUY=99999; 42 | REBUY=TSBUY[1]; 43 | REBUYLIFE=2; 44 | END; 45 | IF (H>=REBUY[1] AND MP[1]=0) OR REBUYLIFE<=0 THEN BEGIN 46 | REBUY=99999; 47 | REBUYLIFE=0; 48 | END; 49 | IF REBUYLIFE>0 AND MP=0 AND MP[1]=0 THEN Buy("TS-ReBuy") Next Bar REBUY STOP; 50 | IF L<=TSSELL[1] THEN BEGIN 51 | TSSELL=0; 52 | RESELL=TSSELL[1]; 53 | RESELLLIFE=2; 54 | END; 55 | IF (L<=RESELL[1] AND MP[1]=0) OR RESELLLIFE<=0 THEN BEGIN 56 | RESELL=0; 57 | RESELLLIFE=0; 58 | END; 59 | IF RESELLLIFE>0 AND MP=0 AND MP[1]=0 THEN Sell Short("TS-ReSell") Next Bar RESELL STOP; 60 | 61 | IF CDAYS>LEN THEN BEGIN 62 | IF HH>0 AND NEWH>=PREV AND IDHIGH>HH AND SGO THEN BEGIN 63 | TSSELL=HH-ENTRYADD; 64 | Sell Short("TS-Sell") Next Bar TSSELL STOP; 65 | SGO=FALSE; 66 | END; 67 | IF LL>0 AND NEWL>=PREV AND IDLOW TSBUY=LL+ENTRYADD; 68 | Buy("TS-Buy") Next Bar TSBUY STOP; 69 | LGO=FALSE; 70 | END; 71 | END; 72 | END; 73 | Sell("Initial LX") Next Bar IDLOW STOP; 74 | Buy to Cover("Initial SX") Next Bar IDHIGH STOP; 75 | -------------------------------------------------------------------------------- /strats/一个稳定盈利的日内交易系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB一个稳定盈利的日内交易系统代码 2 | 3 | 两天我发过一篇帖子介绍了hans123系统,今天我给大家来点硬货,一个实实在在稳定盈利的日内系统,其中还有很大完善空间,由于我学TB刚刚一周多,技术方面还不是很熟练,希望各位程序高手协助我完善系统,我很喜欢国外论坛的那种氛围,交易高手分享他们的思路和ea雏形,程序高手无偿的帮助他们实现他们的想法,在这个过程中相互提高.再此我希望更多高手分享他们系统的源码,以此来相互提高,让我们早日超过欧美同行的水平.恩,我以为真正掌握交易之道的人是不怕分享他们的思路和系统的,因为一个失效的系统略加修改就可以成为一个稳定获利的系统.为了证明这一点我将在接下来的文章中公布一个和这个系统完全相反的系统,你会发现只要调整交易周期和参数,系统就可以稳定获利.道家说道可道,非常道.名可名,非常名.无,曰天地始.有,曰万物主.常无,欲观其妙.常有,欲关其缴.玄之又玄,众妙之门.用在交易系统上来说就是可以写出来的系统肯定不是永远有效的系统,只有掌握了交易之道的人,才能随着市场变化调整他的交易策略.永远与道同在.所谓常无,就是要经常抛弃以前的所有的理论和观念,以客观观察市场的奥妙.常有,就是要带着你以前设计交易系统的经验和技巧.去审视你现在所用的系统.谨以此篇献给各位交易市场的新手老手.希望我们大家一起合作,制作出一个完善可靠的交易系统来.就算没有任何系统经验的人也来分享一下你们的想法,很多时候新手的一句话也是我灵感的源泉.实在不知道说啥的就帮顶一下吧,此帖能一直置顶我就每周发一个交易系统,呵呵.不废话了,开始说代码和思路. 4 | ***1基本思路:RangeBreak加入交易时间过滤,多周期趋势过滤,突破range过滤.Range优化. 5 | 参加过高级应用培训的人应该很熟悉这个系统,这是我在外汇市场用了很久的系统,想移植到国内来,通过搜索找到了培训的文档.然后写了出来,发现效果不是很好,于是我就对其进行了优化,优化的结果还是相当不错的资金曲线稳定增长,利润也不小,大家可以自己测试一下.用于股指期货铜,锌等品种的15分钟都是相当不错的。恩下面叙述一下基本的交易思路。 6 | 以昨日震幅为基础,今日开盘价+N*昨日震幅等于上轨 今日开盘价-昨日震幅*N等于下轨,突破上轨做多突破下轨做空。反之平仓,14点55分平掉所有仓位。N=0.8 7 | 已完成优化的思路 8 | 1。限制交易时间,最后开仓时间在下午两点以前(根据观察接近收盘的突破一般是无效的) 9 | 2。限制前一日的最小震幅(根据观察昨日震幅太小的话会出现很多无效信号) 10 | 未完成的交易思路 各位高手前辈不吝赐教协助我完成下哈。 11 | 1。根据观察与大周期趋势相反的突破一般来说是假突破。限制大周期趋势方法,日线n周期ma方向. 12 | 处理方法: 13 | 1.过滤掉所有与大周期趋势相反的信号 14 | 2.所有大周期相反的信号反向操作既原来做空现在做多,原来做多现在做空。 15 | 根据我外汇自动交易的经验处理方法2更加有效,但编程比较复杂希望高手能帮助我完成这两个思路的编程。 16 | PS:大家有什么进一步优化这个系统的思想也可以提出来我会尽我所能去实现它。 17 | 代码缺陷: 18 | 14点55分平仓在15分钟不能运行,在1分钟运行正常。不明白为什么,请高手赐教。 19 | 有其它缺陷大家也请提出来 20 | 21 | 22 | 23 | 24 | 具体源码 25 | 26 | 27 | //------------------------------------------------------------------------ 28 | // 简称: RB 29 | // 名称:15Min RangeBreak 30 | // 类别: 交易指令 31 | // 类型: 其他 32 | // 输出: 33 | //------------------------------------------------------------------------ 34 | Params 35 | Numeric PercentOfRange(0.8);//突破参数N 36 | Numeric ExitOnCloseMins(14.55);//平仓时间 37 | Numeric MinRange(0.2);//最小Range 38 | Numeric LastTradeMins(14.00);//最后交易时间 39 | Numeric BeginTradeMins(9.00); 40 | Numeric Lots(1); 41 | Numeric Stoplossset(1); 42 | Vars 43 | NumericSeries DayOpen; 44 | NumericSeries preDayRange; 45 | NumericSeries HigherAfterEntry; 46 | NumericSeries LowerAfterEntry; 47 | Numeric preDayHigh; 48 | Numeric preDayLow; 49 | Numeric UpperBand; 50 | Numeric LowerBand; 51 | Numeric MyPrice; 52 | Numeric StopLine; 53 | Begin 54 | DayOpen=OpenD(0); 55 | preDayHigh=HighD(1); 56 | preDayLow=LowD(1); 57 | preDayRange=HighD(1)-LowD(1); 58 | UpperBand=DayOpen+preDayRange*PercentOfRange; 59 | LowerBand=Dayopen-preDayRange*PercentOfRange; 60 | If(BarsSinceEntry==1) 61 | { 62 | HigherAfterEntry=AvgEntryPrice; 63 | LowerAfterEntry=HigherAfterEntry; 64 | }Else If(BarsSinceEntry>1) 65 | { 66 | HigherAfterEntry=max (HigherAfterEntry[1],High[1]); 67 | LowerAfterEntry=min(LowerAfterEntry[1],Low[1]); 68 | } 69 | If(Date!=Date[1]) 70 | {DayOpen=Open; 71 | preDayRange=preDayHigh-preDayLow; 72 | If(preDayRange=UpperBand&&TimeMyprice)Myprice=Open; 83 | Buy(1,Myprice); 84 | Return; 85 | } 86 | If(MarketPosition!=1&&Low<=LowerBand&&Time=ExitOnCloseMins/100) 107 | { 108 | Sell(1,Open); 109 | BuyToCover(1,Open); 110 | } 111 | SetExitOncLOSE; 112 | End 113 | -------------------------------------------------------------------------------- /strats/一致趋势下的股指期货交易策略——股指期货短线交易策略研究系列之三.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harvey1673/pyktrader/9e4f9211cb716786d443f3800010d901bc261610/strats/一致趋势下的股指期货交易策略——股指期货短线交易策略研究系列之三.pdf -------------------------------------------------------------------------------- /strats/上唇下鄂指标+交易策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者上唇下鄂指标+交易策略源码 2 | 3 | Vars 4 | NumericSeries MidPrice; // 定义变量用于保存高低价的平均值。 5 | NumericSeries Value1; // 定义变量用于保存SMA值 6 | NumericSeries Value2; // 定义变量用于保存SMA值 7 | NumericSeries Value3; // 定义变量用于保存SMA值 8 | NumericSeries Value4; // 用来保存中间变量 9 | Begin 10 | MidPrice = (High + Low)/2; 11 | Value1 = SMA(MidPrice,5); 12 | Value2 = SMA(MidPrice,8); 13 | Value3 = SMA(MidPrice,13); 14 | 15 | PlotNumeric("上唇",Value1[3]); 16 | PlotNumeric("牙齿",Value2[5]); 17 | PlotNumeric("下颚",Value3[8]); 18 | 19 | Value4 = Value2[5]; 20 | If(CrossOver(Close,Value4)) 21 | { 22 | PlotNumeric("BuySignal",Low); 23 | } 24 | 25 | If(CrossUnder(Close,Value4)) 26 | { 27 | PlotNumeric("SellSignal",High); 28 | } 29 | End 30 | 31 | 32 | 思路是这样的,当价格从上往下穿越牙齿的时候开空单并且平掉多单,股价从下往上穿越牙齿的时候开多单并且平掉空单, 33 | 34 | 35 | 36 | 37 | 38 | 39 | =================================================================== 40 | 41 | 42 | 上唇下鄂交易策略源码: 43 | 44 | Vars 45 | 46 | NumericSeries MidPrice; // 定义变量用于保存高低价的平均值。 47 | 48 | NumericSeries Value1; 49 | 50 | NumericSeries Value2; 51 | 52 | Begin 53 | 54 | MidPrice = (High + Low)/2; 55 | 56 | Value1 = SMA(MidPrice,8); 57 | 58 | Value2 = Value1[5]; 59 | 60 | If(CrossOver(Close,Value2)) 61 | 62 | { 63 | 64 | Buy(1,Close); 65 | 66 | } 67 | 68 | 69 | 70 | If(CrossUnder(Close,Value2)) 71 | 72 | { 73 | 74 | SellShort(1,Close); 75 | 76 | } 77 | 78 | End -------------------------------------------------------------------------------- /strats/交易开拓者日内高低点突破交易系统.txt: -------------------------------------------------------------------------------- 1 | 交易开拓者日内高低点突破交易系统 模型 源码[开拓者公式] 2 | 3 | / 简称: todayHLCross 4 | // 名称: 5 | // 类别: 交易指令 6 | // 类型: 其他 7 | // 输出: 8 | //------------------------------------------------------------------------ 9 | /* 10 | 日内开盘区高低点机械突破系统 11 | */ 12 | Params 13 | Numeric maxLots(1);//单次 开仓手数 14 | Numeric maxTrad(4);//最大交易次数 15 | Numeric minSpt(15);//最小开仓间隔bar数 16 | Numeric splitRate(3); //交易滑点和佣金 17 | 18 | Numeric tradBegin(930); //开仓 时间 19 | Numeric tradEnd(1430); //开仓截止时间 20 | Numeric closeTime(1457); //bar的时间超过此值后 平仓,一分钟交易=1457 21 | Vars 22 | Numeric splitDot; //交易滑点 23 | 24 | Bool bc(False);//开多条件 25 | Bool sc(False);//开空条件 26 | 27 | Numeric tradePrice(0); 28 | 29 | NumericSeries hh; 30 | NumericSeries ll; 31 | 32 | 33 | Begin splitDot=splitRate*MinMove(); If(BarStatus==0) { hh=High; ll=Low; Return; } if(Day !=Day[1]) { hh=High; ll=Low; } Else If(Time0.0001*tradBegin) { if(Highhh[1]) hh=High; Else hh=hh[1]; if(Lowll[ 34 | 35 | Begin 36 | splitDot=splitRate*MinMove(); 37 | 38 | If(BarStatus==0) 39 | { 40 | hh=High; 41 | ll=Low; 42 | Return; 43 | } 44 | 45 | if(Day !=Day[1]) 46 | { 47 | hh=High; 48 | ll=Low; } 49 | Else 50 | If(Time<0.0001*tradBegin) 51 | { 52 | if(High>hh[1]) hh=High; Else hh=hh[1]; 53 | if(Low=0.0001*tradBegin And Time<=0.1500) 57 | { 58 | hh=hh[1]; 59 | ll=ll[1]; 60 | 61 | //穿越模式 62 | bc=CrossOver(Open,hh) Or CrossOver(High,hh) Or CrossOver(Low,hh) Or CrossOver(Close,hh) ; 63 | sc=CrossUnder(Open,ll) Or CrossUnder(High,ll) Or CrossUnder(Low,ll) Or CrossUnder(Close,ll); 64 | 65 | if(MarketPosition == 0) 66 | { 67 | // 当前无仓,开始建立多头 68 | if(bc) 69 | { 70 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 71 | Buy(maxLots,tradePrice); 72 | } 73 | Else 74 | // 当前无仓,开始建立空头 75 | If(sc ) 76 | { 77 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 78 | SellShort(maxLots,tradePrice); 79 | } 80 | //----------------------------------------------------------------------------- Else { if(MarketPosition 0 ) { // 当前多仓,加仓多头 if(bc And BarsSinceLastEntryminSpt) { if(BarStatus==2) tradePrice= 81 | 82 | //----------------------------------------------------------------------------- 83 | Else 84 | { 85 | if(MarketPosition > 0 ) 86 | { 87 | // 当前多仓,加仓多头 88 | if(bc And BarsSinceLastEntry>minSpt) 89 | { 90 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 91 | Buy(maxLots,tradePrice); 92 | } 93 | // 当前多头,要求反转为空头 94 | if(sc) 95 | { 96 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 97 | 98 | // 平多头开空 99 | SellShort(maxLots,tradePrice); 100 | } 101 | //持仓处理, 止损 止盈平仓 102 | //........ 103 | } 104 | //----------------------------------------------------------------------------------------------- 105 | Else 106 | if(MarketPosition < 0 ) 107 | { 108 | // 当前空仓,加空头 109 | If(sc And BarsSinceLastEntry>minSpt) 110 | { 111 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 112 | SellShort(maxLots,tradePrice); 113 | } 114 | // 当前空头,要求反转为多头 115 | if(bc) 116 | { 117 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 118 | //平空头,开多 119 | Buy(maxLots,tradePrice); 120 | } 121 | //持仓处理,止损止盈平仓 122 | //........ 123 | } 124 | } 125 | } 126 | End 127 | //------------------------------------------------------------------------ 128 | 129 | 130 | } -------------------------------------------------------------------------------- /strats/全自动动态突破型交易系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者全自动动态突破型交易系统源码 2 | 3 | //源码: 4 | 5 | Params 6 | Numeric ceilingAmt(60); 7 | Numeric floorAmt(20); 8 | Numeric bolBandTrig(2.00); 9 | Vars 10 | Numeric lookBackDays(20); 11 | Numeric todayVolatility(0); 12 | Numeric yesterDayVolatility(0); 13 | Numeric deltaVolatility(0); 14 | NumericSeries buyPoint(0); 15 | NumericSeries sellPoint(0); 16 | NumericSeries longLiqPoint(0); 17 | NumericSeries shortLiqPoint(0); 18 | Numeric upBand(0); 19 | Numeric dnBand(0); 20 | Numeric MidLine(0); 21 | Numeric Band(0); 22 | Begin 23 | todayVolatility = StandardDev(Close,30,1); 24 | yesterDayVolatility = StandardDev(Close[1],30,1); 25 | deltaVolatility = (todayVolatility - yesterDayVolatility)/todayVolatility; 26 | lookBackDays = lookBackDays * (1 + deltaVolatility); 27 | lookBackDays = Round(lookBackDays,0); 28 | lookBackDays = Min(lookBackDays,ceilingAmt); 29 | lookBackDays = Max(lookBackDays,floorAmt); 30 | MidLine = AverageFC(Close,lookBackDays); 31 | Band = StandardDev(Close,lookBackDays,bolBandTrig); 32 | upBand = MidLine + bolBandTrig * Band; 33 | dnBand = MidLine - bolBandTrig * Band; 34 | buyPoint = Highest(High[1],lookBackDays); 35 | sellPoint = Lowest(Low[1],lookBackDays); 36 | longLiqPoint = Average(Close[1],lookBackDays); 37 | shortLiqPoint = Average(Close[1],lookBackDays); 38 | if(Close > upBand) 39 | { 40 | If(CrossOver(high,buyPoint)) 41 | { 42 | Buy(1,max( buyPoint, Low )); 43 | } 44 | Commentary("多头触发价:"+Text(buyPoint)); 45 | } 46 | if(Close < dnBand) 47 | { 48 | If(CrossUnder(Low,sellPoint )) 49 | { 50 | SellShort(1,min( sellPoint , High )); 51 | } 52 | Commentary("空头触发价:"+Text(sellPoint)); 53 | } 54 | if(MarketPosition == 1) 55 | { 56 | If(CrossUnder(Low,longLiqPoint )) 57 | { 58 | Sell(1,min( longLiqPoint , High )); 59 | } 60 | Commentary("多头退出:"+Text(longLiqPoint)); 61 | } 62 | 63 | 64 | if(MarketPosition == -1) 65 | { 66 | If(CrossOver(high,shortLiqPoint)) 67 | { 68 | BuyToCover(1,max( shortLiqPoint, Low )); 69 | } 70 | Commentary("空头退出:"+Text(shortLiqPoint)); 71 | } 72 | 73 | End -------------------------------------------------------------------------------- /strats/分形操作突破法.txt: -------------------------------------------------------------------------------- 1 | 开拓者 分形操作突破法 系统 模型 源码[开拓者公式] 2 | 3 | 交易开拓者TB分形操作突破法 系统 模型 源码: 4 | 5 | Params 6 | Numeric length1(8); 7 | Numeric length2(5); 8 | Vars 9 | Numeric CHI; 10 | NumericSeries AA; 11 | Numeric BarNumsA; 12 | Numeric BarNumsB; 13 | Numeric HH; 14 | Numeric LL; 15 | Begin 16 | AA=SMA((High+Low+Close)/3,length1); 17 | CHI=AA[length2]; 18 | BarNumsA=NthCon((High>HighD[1] && High>HighD[2] && High>=NextHigh),1); 19 | HH=HighD[BarNumsA]; 20 | BarNumsB=NthCon((LowHH) 23 | {Buy(1,NextClose,true);} 24 | If(CloseBand; 56 | If (SellEntrysignal) // 正向套利,期指开空单,买入现货 57 | 58 | { 59 | // 开仓价格取开盘价加上一个单位滑点,这样能更接近真实情况,并能尽量保证成交 60 | myEntryPrice = Open-MinPoint; 61 | Sellshort(Lots,myEntryPrice); 62 | } 63 | 64 | BuyEntrysignal=st1[1]<(-1)*Band; 65 | If (BuyEntrysignal) // 反向套利,期指开多单,卖出现货 66 | 67 | { 68 | 69 | // 开仓价格取开盘价加上一个单位滑点,这样能更接近真实情况,并能尽量保证成交 70 | myEntryPrice = Open+MinPoint; 71 | Buy(Lots,myEntryPrice); 72 | 73 | } 74 | 75 | SellExitsignal=CrossUnder(st1[1],0); 76 | if( SellExitsignal && MarketPosition == -1 ) // 正向套利平仓,期指空单平,卖出现货 77 | 78 | { 79 | 80 | // 开仓价格取开盘价加上一个单位滑点,这样能更接近真实情况,并能尽量保证成交 81 | myEntryPrice = Open+MinPoint; 82 | BuyToCover(Lots,myEntryPrice); 83 | 84 | } 85 | 86 | BuyExitsignal=CrossOver(st1[1],0); 87 | 88 | if (BuyExitsignal && marketposition==1) // 反向套利平仓,期指多单平,买入现货 89 | { 90 | 91 | // 开仓价格取开盘价加上一个单位滑点,这样能更接近真实情况,并能尽量保证成交 92 | 93 | myEntryPrice = Open-MinPoint; 94 | 95 | Sell(Lots,myEntryPrice); 96 | 97 | } 98 | 99 | 100 | 101 | End -------------------------------------------------------------------------------- /strats/回抽开仓多空模型.txt: -------------------------------------------------------------------------------- 1 | 回抽开仓多空模型源码 开拓者TB 文华通用 2 | 3 | 开拓者源码: 4 | 5 | Params 6 | Numeric lenth(10); 7 | Numeric Lots(1); 8 | Numeric ExitOnCloseMins(15.10); 9 | 10 | Vars 11 | Numeric H1; 12 | Numeric H2; 13 | Numeric H3; 14 | Numeric L1; 15 | Numeric L2; 16 | Numeric L3; 17 | Numeric HH; 18 | Numeric LL; 19 | Numeric Stopline; 20 | Numeric C1; 21 | Numeric C2; 22 | Numeric C3; 23 | 24 | Begin 25 | H1=H[1]; 26 | H2=H[2]; 27 | H3=H[3]; 28 | L1=L[1]; 29 | L2=L[2]; 30 | L3=L[3]; 31 | 32 | HH=Highest(High[1],Lenth); 33 | LL=Lowest(Low[1],lenth); 34 | If(H1

H3 && H1>H3 && High>=H2 && MarketPosition!=1) 35 | { 36 | Buy(Lots,Max(Open,H2)); 37 | Return; 38 | } 39 | If(L1>L2 && L20)Sell(Lots,Min(Open,LL)); 47 | If(MarketPosition==-1 && H>=HH && BarsSinceEntry>0)BuyToCover(Lots,Max(Open,HH)); 48 | 49 | If(Time >=ExitOnCloseMins/100) 50 | { 51 | Sell(0,Open); 52 | BuyToCover(0,Open); 53 | } 54 | End 55 | 56 | 57 | 58 | 59 | 文华财经WH3 源码: 60 | 61 | 62 | 63 | H1:=REF(H,1); 64 | H2:=REF(H,2); 65 | H3:=REF(H,3); 66 | L1:=REF(L,1); 67 | L2:=REF(L,2); 68 | L3:=REF(L,3); 69 | HH:=HHV(H1,10); 70 | LL:=LLV(L1,10); 71 | H1

H3 && H1>H3 && HIGH>=H2,BK; 72 | L1>L2 && L2=1510,SP; 74 | H>=HH||TIME>=1510,BP; 75 | AUTOFILTER; -------------------------------------------------------------------------------- /strats/开盘突破日内策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB 简单有效的【开盘突破日内策略】 2 | 3 | 开盘突破日内策略 4 | 5 | 6 | 7 | 类型:日内 8 | 市场:商品期货,外汇 9 | 参考: 完美的日内交易商 10 | 11 | 12 | 一)策略介绍 13 | 开盘15-30分钟的区间具有很大的统计学意义,因为它确定了一天的主要波动区间。如果配合昨日的收盘价,这个区间将更加确定。这在行为金融学中有时被称为‘捆绑效应’。如果这个区间被突破,那么很可能会伴随大阴或大阳。因此,我们是用可控的风险来博取日内的大趋势。这个策略用程序非常好实现。 14 | 15 | 二)入场方式: 16 | 开盘30分钟不进场。30分钟K线走完后,价格突破30分钟高点,做多。若价格突破30分钟低点,做空。一旦当日做多后,平仓后则只可做空;反之相反。收盘强制平仓。所以,单品种每日最大交易次数为2次。 17 | 18 | 三)出场方式: 19 | 3.1 止损砍仓 20 | 实践证明,出场时间的重要程度胜于入场。使用固定百分比或固定点数的止损,果断砍仓。我们不追求胜率,我们只追求把握住大行情,并在行情出现时果断加仓。若在止损后,行情继续突破开盘区间的上轨,不在做多,因为我们预计趋势已经反转;若行情继续突破下轨,我们继续做空。 21 | 22 | 3.2 达到获利目标后使用追踪止损 23 | 如果固定点位的获利已经实现后,我们可以离场。或者,我们可以继续让利润奔跑,但使用追踪止损,防止利润流失。 24 | 25 | 3.3 收盘平仓 26 | 如果一直未被止损出局,则收盘平仓。 27 | 28 | 四)仓位控制 29 | 日内获得超额收益的方法只有一个:加仓。这是有风险的。我一般使用的方法是浮盈加仓。具体的加仓手数可根据各品种回测得到的收益均值和最大回撤决定。具体的方法是:保持预期收益/最大回撤处于一个可控的范围。 30 | 好的日内策略一定有加仓和仓位控制的环节,不然,收益是很有限的。 31 | 32 | 33 | 五)历史收益 34 | 该策略在包括GBPUSD, JPYUSD等多品种下均有好的收益。关键问题是要能坚持跟随系统,只在三个出场点满足时平仓。另外,加仓和止损也是该策略的重点。 -------------------------------------------------------------------------------- /strats/日内开盘区高低点机械突破交易系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者 日内开盘区高低点机械突破交易系统源码 2 | 3 | 4 | //------------------------------------------------------------------------ 5 | // 简称: todayHLCross 6 | // 名称: 7 | // 类别: 交易指令 8 | // 类型: 其他 9 | // 输出: 10 | //------------------------------------------------------------------------ 11 | /* 12 | 日内开盘区高低点机械突破系统 13 | */ 14 | Params 15 | Numeric maxLots(1);//单次开仓手数 16 | Numeric maxTrad(4);//最大交易次数 17 | Numeric minSpt(15);//最小开仓间隔bar数 18 | Numeric splitRate(3); //交易滑点和佣金 19 | 20 | Numeric tradBegin(930); //开仓时间 21 | Numeric tradEnd(1430); //开仓截止时间 22 | Numeric closeTime(1457); //bar的时间超过此值后平仓,一分钟交易=1457 23 | 24 | Vars 25 | Numeric splitDot; //交易滑点 26 | 27 | Bool bc(False);//开多条件 28 | Bool sc(False);//开空条件 29 | 30 | Numeric tradePrice(0); 31 | 32 | NumericSeries hh; 33 | NumericSeries ll; 34 | 35 | Begin 36 | splitDot=splitRate*MinMove(); 37 | 38 | If(BarStatus==0) 39 | { 40 | hh=High; 41 | ll=Low; 42 | Return; 43 | } 44 | 45 | if(Day !=Day[1]) 46 | { 47 | hh=High; 48 | ll=Low; } 49 | Else 50 | If(Time<0.0001*tradBegin) 51 | { 52 | if(High>hh[1]) hh=High; Else hh=hh[1]; 53 | if(Low=0.0001*tradBegin And Time<=0.1500) 57 | { 58 | hh=hh[1]; 59 | ll=ll[1]; 60 | 61 | //穿越模式 62 | bc=CrossOver(Open,hh) Or CrossOver(High,hh) Or CrossOver(Low,hh) Or CrossOver(Close,hh) ; 63 | sc=CrossUnder(Open,ll) Or CrossUnder(High,ll) Or CrossUnder(Low,ll) Or CrossUnder(Close,ll); 64 | 65 | if(MarketPosition == 0) 66 | { 67 | // 当前无仓,开始建立多头 68 | if(bc) 69 | { 70 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 71 | Buy(maxLots,tradePrice); 72 | } 73 | Else 74 | // 当前无仓,开始建立空头 75 | If(sc ) 76 | { 77 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 78 | SellShort(maxLots,tradePrice); 79 | } 80 | } 81 | //----------------------------------------------------------------------------- 82 | Else 83 | { 84 | if(MarketPosition > 0 ) 85 | { 86 | // 当前多仓,加仓多头 87 | if(bc And BarsSinceLastEntry>minSpt) 88 | { 89 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 90 | Buy(maxLots,tradePrice); 91 | } 92 | // 当前多头,要求反转为空头 93 | if(sc) 94 | { 95 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 96 | 97 | // 平多头开空 98 | SellShort(maxLots,tradePrice); 99 | } 100 | //持仓处理,止损止盈平仓 101 | //........ 102 | } 103 | //----------------------------------------------------------------------------------------------- 104 | Else 105 | if(MarketPosition < 0 ) 106 | { 107 | // 当前空仓,加空头 108 | If(sc And BarsSinceLastEntry>minSpt) 109 | { 110 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 111 | SellShort(maxLots,tradePrice); 112 | } 113 | // 当前空头,要求反转为多头 114 | if(bc) 115 | { 116 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 117 | //平空头,开多 118 | Buy(maxLots,tradePrice); 119 | } 120 | //持仓处理,止损止盈平仓 121 | //........ 122 | } 123 | } 124 | } 125 | End 126 | -------------------------------------------------------------------------------- /strats/日内高低点突破交易系统.txt: -------------------------------------------------------------------------------- 1 | 日内高低点突破交易系统[开拓者公式] 2 | 3 | //------------------------------------------------------------------------ 4 | // 简称: todayHLCross 5 | // 名称: 6 | // 类别: 交易指令 7 | // 类型: 其他 8 | // 输出: 9 | //------------------------------------------------------------------------ 10 | /* 11 | 日内开盘区高低点机械突破系统 12 | */ 13 | Params 14 | Numeric maxLots(1);//单次开仓手数 15 | Numeric maxTrad(4);//最大交易次数 16 | Numeric minSpt(15);//最小开仓间隔bar数 17 | Numeric splitRate(3); //交易滑点和佣金 18 | 19 | Numeric tradBegin(930); //开仓时间 20 | Numeric tradEnd(1430); //开仓截止时间 21 | Numeric closeTime(1457); //bar的时间超过此值后平仓,一分钟交易=1457 22 | 23 | Vars 24 | Numeric splitDot; //交易滑点 25 | 26 | Bool bc(False);//开多条件 27 | Bool sc(False);//开空条件 28 | 29 | Numeric tradePrice(0); 30 | 31 | NumericSeries hh; 32 | NumericSeries ll; 33 | 34 | Begin 35 | splitDot=splitRate*MinMove(); 36 | 37 | If(BarStatus==0) 38 | { 39 | hh=High; 40 | ll=Low; 41 | Return; 42 | } 43 | 44 | if(Day !=Day[1]) 45 | { 46 | hh=High; 47 | ll=Low; } 48 | Else 49 | If(Time<0.0001*tradBegin) 50 | { 51 | if(High>hh[1]) hh=High; Else hh=hh[1]; 52 | if(Low=0.0001*tradBegin And Time<=0.1500) 56 | { 57 | hh=hh[1]; 58 | ll=ll[1]; 59 | 60 | //穿越模式 61 | bc=CrossOver(Open,hh) Or CrossOver(High,hh) Or CrossOver(Low,hh) Or CrossOver(Close,hh) ; 62 | sc=CrossUnder(Open,ll) Or CrossUnder(High,ll) Or CrossUnder(Low,ll) Or CrossUnder(Close,ll); 63 | 64 | if(MarketPosition == 0) 65 | { 66 | // 当前无仓,开始建立多头 67 | if(bc) 68 | { 69 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 70 | Buy(maxLots,tradePrice); 71 | } 72 | Else 73 | // 当前无仓,开始建立空头 74 | If(sc ) 75 | { 76 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 77 | SellShort(maxLots,tradePrice); 78 | } 79 | } 80 | //----------------------------------------------------------------------------- 81 | Else 82 | { 83 | if(MarketPosition > 0 ) 84 | { 85 | // 当前多仓,加仓多头 86 | if(bc And BarsSinceLastEntry>minSpt) 87 | { 88 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 89 | Buy(maxLots,tradePrice); 90 | } 91 | // 当前多头,要求反转为空头 92 | if(sc) 93 | { 94 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 95 | 96 | // 平多头开空 97 | SellShort(maxLots,tradePrice); 98 | } 99 | //持仓处理,止损止盈平仓 100 | //........ 101 | } 102 | //----------------------------------------------------------------------------------------------- 103 | Else 104 | if(MarketPosition < 0 ) 105 | { 106 | // 当前空仓,加空头 107 | If(sc And BarsSinceLastEntry>minSpt) 108 | { 109 | if(BarStatus==2)tradePrice= Q_BidPrice -splitDot; Else tradePrice=ll-splitDot; 110 | SellShort(maxLots,tradePrice); 111 | } 112 | // 当前空头,要求反转为多头 113 | if(bc) 114 | { 115 | if(BarStatus==2) tradePrice= Q_AskPrice +splitDot; Else tradePrice=hh+splitDot; 116 | //平空头,开多 117 | Buy(maxLots,tradePrice); 118 | } 119 | //持仓处理,止损止盈平仓 120 | //........ 121 | } 122 | } 123 | } 124 | End 125 | -------------------------------------------------------------------------------- /strats/盈利的交易系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB盈利的交易系统源码 2 | 3 | 系统描述:以10:00那根K线的开盘价作为基准线BaseLine,上下0.25%做为开仓线,10:05开始,如果CLOSE大于BaseLine*(1+0.0025)则开多,小于BaseLine则平仓;如果CLOSE小于BaseLine*(1-0.0025)则开空,大于BaseLine则平仓;14:00以后不再开仓;14:55平持仓。 4 | 5 | 6 | 这个系统超级白痴,没有那么高智能的开仓点选择,也不做平推(如有兴趣也可以实现平推功能)。看看效果如何: 7 | 8 | 9 | 10 | 2011年以来,胜率38.37%,盈亏比2.39,年化收益率214%,当前收益323667,最大回撤44268,总交易次数331,平均单次盈利977. 11 | 12 | if888 5分钟周期测试 双向手续费150 13 | 14 | 15 | 16 | 17 | 盈利交易模型源码: 18 | 19 | Params 20 | 21 | Numeric lots(1); 22 | //Numeric offset(2); //滑点 23 | 24 | Vars 25 | 26 | 27 | NumericSeries Tday(0); 28 | NumericSeries upBand(0); 29 | NumericSeries dnBand(0); 30 | Begin 31 | 32 | if(time>=0.1455) 33 | { 34 | if(MarketPosition==1) 35 | sell(lots,close); 36 | if(MarketPosition==-1) 37 | { 38 | buytocover(lots,close); 39 | 40 | } 41 | Return; 42 | } 43 | 44 | 45 | if(date<>date[1]) 46 | { 47 | Tday=0; 48 | 49 | }Else 50 | { 51 | 52 | if (time==0.1000) 53 | { 54 | Tday=o; 55 | upBand = Tday*(1+0.0025); 56 | dnBand = Tday*(1-0.0025); 57 | 58 | } 59 | 60 | } 61 | 62 | 63 | PlotNumeric("text1",upBand); 64 | PlotNumeric("text2",dnBand); 65 | 66 | 67 | 68 | If(MarketPosition <>1 && Close[1] > upBand && time>0.1005 && time <0.1400) 69 | { 70 | Buy(lots,max( open ,upBand)); 71 | 72 | } 73 | 74 | 75 | 76 | If(MarketPosition <>-1 && Close[1] < dnBand && time>0.1005 && time <0.1400) 77 | { 78 | SellShort(lots,min( open ,dnBand)); 79 | 80 | } 81 | 82 | 83 | 84 | 85 | End 86 | 87 | 88 | -------------------------------------------------------------------------------- /strats/突破+穿越追涨杀跌法交易策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB 突破+穿越追涨杀跌法交易策略源码 2 | 3 | 一小段股指期货(IF)程序,送懂得感恩的人。 4 | 5 | 6 | 7 | 8 | Params 9 | Numeric K1(50); 10 | Numeric K2(7); 11 | Numeric nOffSet(0); 12 | Numeric stopLossSet(100); 13 | 14 | Vars 15 | NumericSeries a1; 16 | NumericSeries a2; 17 | Numeric MinPoint; 18 | Numeric MyEntryPrice; 19 | Numeric MyExitPrice; 20 | Numeric stopLossPoint; 21 | Numeric offSetDots; 22 | bool cross1; 23 | bool cross2; 24 | 25 | Begin 26 | offSetDots = nOffSet * MinMove * PriceScale; 27 | 28 | a1=Highest(high[1],K1); 29 | a2=Lowest(low[1],K2); 30 | 31 | cross1=CrossOver(high,a1); 32 | cross2=CrossUnder(low,a2); 33 | 34 | 35 | 36 | If(cross1 && MarketPosition<>1) 37 | { 38 | Buy(1,a1+offSetDots); 39 | } 40 | If(cross2 && MarketPosition<>-1) 41 | { 42 | SellShort(1,a2-offSetDots); 43 | } 44 | stopLossPoint = stopLossSet * MinMove * PriceScale; 45 | 46 | 47 | If(MarketPosition == 1) 48 | { 49 | 50 | 51 | myEntryPrice = AvgEntryPrice; 52 | 53 | If(low <= myEntryPrice - stopLossPoint) 54 | { 55 | myExitPrice = myEntryPrice - stopLossPoint; 56 | If(open < myExitPrice) myExitPrice = open; 57 | Sell(0,myExitPrice); 58 | } 59 | } 60 | else If (MarketPosition == -1) 61 | { 62 | 63 | myEntryPrice = AvgEntryPrice; 64 | 65 | If(High >= myEntryPrice + stopLossPoint) 66 | { 67 | myExitPrice = myEntryPrice + stopLossPoint; 68 | If(open > myExitPrice) myExitPrice = open; 69 | BuyToCover(0,myExitPrice); 70 | } 71 | } 72 | 73 | 74 | End -------------------------------------------------------------------------------- /strats/简单的波动性突破系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB 简单的波动性突破系统 2 | 3 | /------------------------------------------------------------------------ 4 | 5 | // 简称: ATR_Breaker 6 | 7 | // 名称: 波动性突破系统 8 | 9 | // 类别: 公式应用 10 | 11 | // 类型: 用户应用 12 | 13 | // 输出: 14 | 15 | //------------------------------------------------------------------------ 16 | 17 | Params 18 | 19 | Numeric range(1.5); 20 | 21 | Numeric length(10); 22 | 23 | Numeric N(20); 24 | 25 | Numeric lots(1); 26 | 27 | Vars 28 | 29 | NumericSeries TR; 30 | 31 | NumericSeries ATR; 32 | 33 | Bool DT; 34 | 35 | Bool KT; 36 | 37 | Bool DT2; 38 | 39 | Bool KT2; 40 | 41 | 42 | 43 | Begin 44 | 45 | TR=Max(Max(High-Low,Abs(Close[1]-High)),Abs(Close[1]-Low)); 46 | 47 | ATR=Average(TR,length); 48 | 49 | DT=Close>Close[1]+ATR[1]*range; 50 | 51 | KT=Closema1&&close>ma2&&close[1]min(ma1[1],ma2[1])){ 68 | 69 | cond2=true; 70 | 71 | startbar2=CurrentBar; 72 | 73 | tosell=low; 74 | 75 | } 76 | 77 | If(currentbar-startbar1>filter)cond1=false; 78 | 79 | If(currentbar-startbar2>filter)cond2=false; 80 | 81 | If(MarketPosition!=1&&cond1&&high>=tobuy&¤tbar!=startbar1)Buy(units,max(o,tobuy)); 82 | 83 | If(MarketPosition!=-1&&cond2&&low<=tosell&¤tbar!=startbar2)SellShort(units,min(o,tosell)); 84 | 85 | End -------------------------------------------------------------------------------- /strats/股指3分钟日内支撑阻力位突破交易策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者股指3分钟日内,支撑阻力位突破交易策略源码 2 | 3 | //----------------------------------------------------------------------- 4 | // 简称: 50050402 5 | // 名称: 支撑阻力位突破 6 | // 类别: 公式应用 7 | // 类型: 用户应用 8 | //------------------------------------------------------------------------ 9 | Params 10 | Numeric lostmove(0.20); 11 | 12 | Numeric N(0.70); 13 | 14 | Vars 15 | 16 | Numeric NetChg(0); 17 | Numeric TotChg(0); 18 | NumericSeries EffRatio(0); 19 | NumericSeries AMAValue; //定义效率指数 20 | 21 | NumericSeries HighVanlue(0); //定义高点阻力位; 22 | NumericSeries LowVanlue(0); //定义低点支撑位; 23 | 24 | NumericSeries HigherVanlue(0); //较高高点; 25 | NumericSeries LowerVanlue(0); //较低低点; 26 | 27 | Numeric ATR; 28 | 29 | Begin 30 | 31 | //计算ATR 32 | ATR = AvgTrueRange(20); 33 | 34 | //定义AMA(自适应曲线) 35 | if(CurrentBar == 0) 36 | { 37 | AMAValue = close; 38 | }Else 39 | { 40 | NetChg = Abs( close - close[10] ); 41 | TotChg = Summation( Abs( close - close[1] ), 10); 42 | EffRatio = IIF(TotChg > 0, NetChg / TotChg, 0); 43 | } 44 | 45 | 46 | //三点清零 47 | If(Time==0.1515) 48 | { 49 | HighVanlue=0; 50 | LowVanlue=0; 51 | } 52 | 53 | //定义阻力支撑位 54 | If(Time>0.0930) 55 | { 56 | If(high[3]>high[4]&&High[3]>High[5]&&high[3]>high[2] &&high[3]>high[1]) 57 | { 58 | HighVanlue=high[3]; 59 | } 60 | 61 | If(low[3]EntryPrice+20) 88 | { 89 | BuyToCover(1,EntryPrice+20); 90 | PlotString("Vol","金额止损",Low,Red); 91 | } 92 | 93 | 94 | //顺势平仓 95 | //平多单 96 | If(MarketPosition==1&&LowHighVanlue+lostmove) 111 | { 112 | If(Open>HighVanlue+lostmove) 113 | { 114 | BuyToCover(1,Open+lostmove); 115 | PlotString("Vol","破高",Low,Red); 116 | }Else 117 | { 118 | BuyToCover(1,HighVanlue+lostmove); 119 | PlotString("Vol","破高",Low,Red); 120 | } 121 | } 122 | 123 | //回撤止损 124 | IF(MarketPosition==1&&CloseLowest(Low,BarsSinceEntry)+4*ATR) 131 | { 132 | BuyToCover(1,Close); 133 | PlotString("Vol","ATR",Low,Red); 134 | } 135 | 136 | 137 | //开仓 138 | //顺势突破开仓 139 | If(0.0930HigherVanlue+lostmove&&EffRatio>N) 142 | { 143 | Buy(1,Close); 144 | } 145 | 146 | If(MarketPosition!=-1&&CloseN) 147 | { 148 | SellShort(1,Close); 149 | } 150 | } 151 | 152 | 153 | //收盘平仓 154 | If(MarketPosition==1&&Time>=0.1509) 155 | { 156 | Sell(1,Close); 157 | PlotString("Vol","收盘平仓",Low,Red); 158 | } 159 | 160 | If(MarketPosition==-1&&Time>=0.1509) 161 | { 162 | BuyToCover(1,Close); 163 | PlotString("Vol","收盘平仓",Low,Red); 164 | } 165 | 166 | End -------------------------------------------------------------------------------- /strats/逐风破浪交易系统.txt: -------------------------------------------------------------------------------- 1 | 开拓者逐风破浪交易系统源码 2 | 3 | 源码内容: 4 | 5 | Params 6 | Bool bInitStatus(false);//初始化标志,修改初始仓位时需设置为True 7 | Numeric InitMyRealMp(0);//初始当前仓位,正数表示多单,负数表示空单 8 | Numeric FirstGrid(10);//第一笔交易的间距,最小跳动 9 | Numeric AddGrid(30);//加仓间距,最小跳动 10 | Numeric TotalGrids(10);//最大交易次数 11 | Numeric TrailingGrid(10);//移动止损间距,最小跳动 12 | Numeric EveryLots(1);//每次开仓手数 13 | Numeric OffSet(1);//委托价偏差,默认买卖价偏差1个滑点 14 | Numeric ExitOnCloseMins(15.00);//收盘平仓时间 15 | Vars 16 | Numeric HighAfterlongEntry; 17 | Numeric LowAfterShortEntry; 18 | Numeric MyRealMp(0); 19 | Numeric MinPoint; 20 | Numeric TmpPrice; 21 | Numeric TmpLots; 22 | Begin 23 | MinPoint=MinMove*PriceScale;//当前商品最小变动量*当前商品的计数单位 24 | MyRealMp=GetGlobalVar(0); //获取MyRealMp全局变量值 25 | HighAfterlongEntry=GetGlobalVar(1); 26 | LowAfterShortEntry=GetGlobalVar(2); 27 | If(BarStatus==0 And (MyRealMp==InvalidNumeric||bInitStatus)) 28 | {MyRealMp=InitMyRealMp;} 29 | If(Date<>Date[1]) 30 | {HighAfterlongEntry=High; 31 | LowAfterShortEntry=Low; 32 | MyRealMp=0; 33 | }Else 34 | {HighAfterlongEntry=Max(HighAfterlongEntry,High); 35 | LowAfterShortEntry=Min(LowAfterShortEntry,Low);} 36 | if (Time0 And HighAfterlongEntry-Low>=TrailingGrid*MinPoint And(High-Low=TrailingGrid*MinPoint And Close=TrailingGrid*MinPoint And (High-Low=TrailingGrid*MinPoint And Close>Open))) 45 | {TmpPrice=Min(LowAfterShortEntry+(TrailingGrid+OffSet)*MinPoint,High); 46 | TmpLots=Abs(MyRealMp*EveryLots); 47 | BuyToCover(TmpLots,TmpPrice); 48 | MyRealMp=0; 49 | HighAfterLongEntry=0;} 50 | If(MyRealMp==0 And High-LowAfterShortEntry>=FirstGrid*MinPoint)//第一笔多单开仓 51 | {TmpPrice=Min(LowAfterShortEntry+(FirstGrid+OffSet)*MinPoint,High); 52 | TmpLots=EveryLots; 53 | Buy(TmpLots,TmpPrice); 54 | MyRealMp=1; 55 | HighAfterLongEntry=High; 56 | }Else 57 | If(MyRealMp>0 And MyRealMp=(FirstGrid+MyRealMp*AddGrid)*MinPoint)//多单加仓 58 | {TmpPrice=Min(LowAfterShortEntry+(FirstGrid+MyRealMp*AddGrid+OffSet)*MinPoint,High); 59 | TmpLots=EveryLots; 60 | Buy(TmpLots,TmpPrice); 61 | MyRealMp=MyRealMp+1; 62 | }else 63 | If(MyRealMp==0 And HighAfterLongEntry-Low>=FirstGrid*MinPoint)//第一笔空单开仓 64 | {TmpPrice=Max(HighAfterLongEntry-(FirstGrid-OffSet)*MinPoint,Low); 65 | TmpLots=EveryLots; 66 | SellShort(TmpLots,TmpPrice); 67 | MyRealMp=-1; 68 | LowAfterShortEntry=Low; 69 | }else 70 | If(MyRealMp<0 And -1*MyRealMp=(FirstGrid+Abs(MyRealMp*AddGrid))*MinPoint)//空单加仓 71 | {TmpPrice=Max(HighAfterLongEntry-(FirstGrid-Abs(MyRealMp*AddGrid)-OffSet)*MinPoint,Low); 72 | TmpLots=EveryLots; 73 | SellShort(TmpLots,TmpPrice); 74 | MyRealMp=MyRealMp-1;} 75 | }else 76 | If(Time>=ExitOnCloseMins/100) 77 | {If(MyRealMp>0) 78 | {TmpLots=Abs(MyRealMp*EveryLots); 79 | TmpPrice=Close; 80 | Sell(0,TmpPrice); 81 | MyRealMp=0;} 82 | If(MyRealMp<0) 83 | {TmpLots=Abs(MyRealMp*EveryLots); 84 | TmpPrice=Close; 85 | BuyToCover(0,TmpPrice); 86 | MyRealMp=0;}} 87 | SetGlobalVar(0,MyRealMp); 88 | SetGlobalVar(1,HighAfterLongEntry); 89 | SetGlobalVar(2,LowAfterShortEntry); 90 | Commentary("MyRealMp="+Text(MyRealMp)); 91 | Commentary("HighAfterLLowAfterShortEntry="+Text(LowAfterShortEntry)); 92 | End 93 | 94 | 95 | -------------------------------------------------------------------------------- /strats/震荡+趋势混合策略恒温器策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者 TB 【震荡+趋势混合策略】恒温器策略【 2 | 3 | 【震荡+趋势混合策略】恒温器策略 4 | 5 | by RogarZ 6 | 7 | 源码: 8 | 9 | 10 | Params 11 | 12 | Numeric bollinglengths(50); 13 | 14 | Numeric trendliqlength(50); 15 | 16 | Numeric numstddevs(2); 17 | 18 | Numeric swingprcnt1(0.5); 19 | 20 | Numeric swingprcnt2(0.75); 21 | 22 | Numeric atrlength(10); 23 | 24 | Numeric swingtrendswitch(50); 25 | 26 | Vars 27 | 28 | BoolSeries swing(False); 29 | 30 | NumericSeries cmival; 31 | 32 | NumericSeries buyeasierday(0); 33 | 34 | NumericSeries selleasierday(0); 35 | 36 | NumericSeries trendlokbuy; 37 | 38 | NumericSeries trendloksell; 39 | 40 | NumericSeries trendbuypt; 41 | 42 | NumericSeries trendsellpt; 43 | 44 | NumericSeries keyofday; 45 | 46 | NumericSeries ma1; 47 | 48 | NumericSeries midd; 49 | 50 | Numeric swingprotstop; 51 | 52 | Numeric atr; 53 | 54 | Numeric swingbuypt; 55 | 56 | Numeric swingsellpt; 57 | 58 | Begin 59 | 60 | Commentary("BarInterval= "+Text(BarInterval)); 61 | 62 | cmival=Abs(Close[1]-Close[31])/(Highest(High[1],30)-Lowest(Low[1],30)); 63 | 64 | trendloksell=Average(Low[1],3*240/BarInterval); 65 | 66 | trendlokbuy=Average(High[1],3*240/BarInterval); 67 | 68 | keyofday=(HighD(0)+LowD(0)+CloseD(0))/3; 69 | 70 | If(Date<>Date[1]){ 71 | 72 | If(CloseD(1)>keyofday[1]) 73 | 74 | { 75 | 76 | selleasierday=1;//空头日 77 | 78 | }Else{ 79 | 80 | buyeasierday=1;//多头日 81 | 82 | } 83 | 84 | } 85 | 86 | Atr=XAverage(TrueRange,atrlength*240/BarInterval); 87 | 88 | If(buyeasierday==1){ 89 | 90 | swingbuypt=OpenD(0)+swingprcnt1*atr; 91 | 92 | swingsellpt=OpenD(0)-swingprcnt2*atr; 93 | 94 | } 95 | 96 | If(selleasierday==1){ 97 | 98 | swingbuypt=OpenD(0)+swingprcnt2*atr; 99 | 100 | swingsellpt=OpenD(0)-swingprcnt1*atr; 101 | 102 | } 103 | 104 | swingbuypt=Max(swingbuypt,trendlokbuy); 105 | 106 | swingsellpt=Min(swingsellpt,trendloksell); 107 | 108 | 109 | 110 | PlotNumeric("Buy",swingbuypt); 111 | 112 | PlotNumeric("Sell",swingsellpt); 113 | 114 | 115 | 116 | ma1=Average(Close[1],trendliqlength);//趋势均线 117 | 118 | midd=Average(Close[1],bollinglengths);//布林中线 119 | 120 | trendbuypt=midd+numstddevs*StandardDev(Close[1],bollinglengths); 121 | 122 | trendsellpt=midd-numstddevs*StandardDev(Close[1],bollinglengths); 123 | 124 | 125 | 126 | If(cmival=swingbuypt) 131 | 132 | //开多仓 133 | 134 | { 135 | 136 | Buy(1,Max(Open,swingbuypt)); 137 | 138 | swing=True; 139 | 140 | } 141 | 142 | If(MarketPosition==0&&Low[1]<=swingsellpt) 143 | 144 | //开空仓 145 | 146 | { 147 | 148 | SellShort(1,Min(Open,swingsellpt)); 149 | 150 | swing=True; 151 | 152 | } 153 | 154 | If(MarketPosition>0&&Low[1]<=swingsellpt) 155 | 156 | //多头反手 157 | 158 | { 159 | 160 | SellShort(1, Min(Open,swingsellpt)); 161 | 162 | swing=True; 163 | 164 | } 165 | 166 | If(MarketPosition<0&&High[1]>=swingbuypt) 167 | 168 | //空头反手 169 | 170 | { 171 | 172 | Buy(1, Max(Open,swingbuypt)); 173 | 174 | swing=True; 175 | 176 | } 177 | 178 | }Else{ 179 | 180 | swingprotstop=atr*3; 181 | 182 | If(MarketPosition==0&&High[1]>=trendbuypt) 183 | 184 | //开多仓 185 | 186 | { 187 | 188 | Buy(1,Max(Open,trendbuypt)); 189 | 190 | swing=False; 191 | 192 | } 193 | 194 | If(MarketPosition==0&&Low[1]<=trendsellpt) 195 | 196 | //开空仓 197 | 198 | { 199 | 200 | SellShort(1,Min(Open,trendsellpt)); 201 | 202 | swing=False; 203 | 204 | } 205 | 206 | If(MarketPosition>0&&swing) 207 | 208 | //多头止损 209 | 210 | { 211 | 212 | If(Low[1]<=EntryPrice-swingprotstop) 213 | 214 | { 215 | 216 | Sell(1,Min(Open, EntryPrice-swingprotstop)); 217 | 218 | }Else If(Low[1]<=ma1) 219 | 220 | { 221 | 222 | Sell(1,Min(Open,ma1)); 223 | 224 | } 225 | 226 | } 227 | 228 | If(MarketPosition<0&&swing) 229 | 230 | //空头止损 231 | 232 | { 233 | 234 | If(High[1]>=EntryPrice+swingprotstop) 235 | 236 | { 237 | 238 | BuyToCover(1,Max(Open, EntryPrice+swingprotstop)); 239 | 240 | }Else If(High[1]>=ma1) 241 | 242 | { 243 | 244 | BuyToCover (1,Max(Open,ma1)); 245 | 246 | } 247 | 248 | } 249 | 250 | } 251 | 252 | End -------------------------------------------------------------------------------- /strats/顺势指标交易策略源码.txt: -------------------------------------------------------------------------------- 1 | TB顺势指标交易策略源码[开拓者公式] 2 | 3 | //------------------------------------------------------------------------ 4 | // 简称: CCIapply 5 | // 名称: 顺势指标 6 | // 类别: 公式应用 7 | // 类型: 用户应用 8 | // 来源: WW.CXH99.COM 9 | //------------------------------------------------------------------------ 10 | 11 | Params 12 | Numeric Para1(10); 13 | Numeric Para2(5); 14 | Numeric Length(14); 15 | Numeric AvgLength(9); 16 | Vars 17 | 18 | Bool Condition1; 19 | Bool Condition2; 20 | Bool PreBreakoutFailure; 21 | NumericSeries TmpValue; 22 | Numeric Mean( 0 ); 23 | Numeric AvgDev( 0 ); 24 | Numeric Counter( 0 ) ; 25 | NumericSeries CCIValue(0); 26 | NumericSeries CCIAvg; 27 | Numeric ExitLowestPrice; 28 | Numeric myEntryPrice; // 开仓价格 29 | Numeric myExitPrice; // 平仓价格 30 | NumericSeries preEntryPrice(0); // 前一次开仓的价格 31 | 32 | Begin 33 | 34 | 35 | TmpValue = High + Low + Close; 36 | Mean = AverageFC( TmpValue, Length ) ; 37 | 38 | AvgDev = 0 ; 39 | for Counter = 0 to Length - 1 40 | { 41 | AvgDev = AvgDev + Abs( TmpValue[Counter] - Mean ) ; 42 | } 43 | AvgDev = AvgDev / Length ; 44 | 45 | if( AvgDev == 0) 46 | CCIValue = 0; 47 | Else 48 | CCIValue = ( TmpValue - Mean ) / ( 0.015 * AvgDev ) ; //求CCI值 49 | CCIAvg = AverageFC(CCIValue, AvgLength ); 50 | 51 | If(BarStatus == 0) 52 | { 53 | preEntryPrice = InvalidNumeric; 54 | PreBreakoutFailure = false; 55 | } 56 | 57 | 58 | Condition1 =CCIValue>=CCIAvg&&CCIValue[1]CCIAvg[1]; 60 | 61 | If(Condition1) 62 | { 63 | if (MarketPosition==-1) 64 | { 65 | myExitPrice=c; 66 | Commentary("myExitPrice="+Text(myExitPrice)); 67 | BuyToCover(1,c); 68 | } 69 | if (MarketPosition==0) 70 | { 71 | myEntryPrice=Data0.close; 72 | Commentary("myEntryPrice="+Text(myEntryPrice)); 73 | Buy(1,close); 74 | } 75 | } 76 | 77 | If(Condition1) 78 | { 79 | If(MarketPosition==1) 80 | { 81 | myExitPrice=c; 82 | Commentary("myExitPrice="+Text(myExitPrice)); 83 | Sell(1,c); 84 | } 85 | If (MarketPosition==0) 86 | { 87 | myEntryPrice=Data0.close; 88 | Commentary("myEntryPricePrice="+Text(myEntryPrice)); 89 | SellShort(1,close); 90 | } 91 | } 92 | End 93 | -------------------------------------------------------------------------------- /strats/顺势模型源码.txt: -------------------------------------------------------------------------------- 1 | 开拓者顺势模型源码 2 | 3 | 排查:1.基本的公式计算. 2.系统的函数. 4 | 5 | 针对:1.RSV这个是标准的KD代码,我只是简单的移植,这个出问题的概率不大. 6 | 我查了下资料,有2种说法,一是说是crossover有问题,我看了下别人的源码,也有用crossover.为了避免K=D的假信号,我用必须'大于'(或者是小于)来过滤假信号. 7 | 8 | 2.就是大家诟病的close函数,这个我正在换算法.或者换其它函数. 现在用的是open等结果. 9 | 10 | 11 | //源码: 12 | Params 13 | Numeric Length(30); //N 30 14 | Numeric SlowLength(10); //M1 15 | Numeric SmoothLength(10); //M2 16 | Numeric lots(1); 17 | Numeric offset(2); 18 | Numeric Stoploss(40); 19 | 20 | Vars 21 | NumericSeries HighestValue; 22 | NumericSeries LowestValue; 23 | NumericSeries KValue;//TB中的K值 24 | NumericSeries DValue;//TB中的K值 25 | NumericSeries RSV; 26 | NumericSeries K1;//正规的K值 27 | NumericSeries D1;//正规的D值 28 | Numeric i_offset; 29 | Numeric BuyPosition; 30 | Numeric SellPosition; 31 | Numeric myEntryPrice; 32 | Numeric myExitPrice; 33 | 34 | Begin 35 | { 36 | HighestValue = HighestFC(High, Length); 37 | LowestValue = LowestFC(Low, Length); 38 | RSV = (Close-LowestValue)/(HighestValue-LowestValue)*100; 39 | K1 = SMA(RSV,SlowLength,1); 40 | D1 = SMA(K1,SmoothLength,1); 41 | KValue = SummationFC(Close - LowestValue,SlowLength)/SummationFC(HighestValue-LowestValue,SlowLength)*100; 42 | DValue = AverageFC(KValue,SmoothLength); 43 | PlotNumeric("RSV",RSV); 44 | 45 | if(MarketPosition == 0) 46 | { 47 | if(K1 > D1) 48 | { 49 | buy(lots,high); //<---原来这里用的buy(lots,close[1]); 50 | Return; 51 | } 52 | } 53 | else if (MarketPosition == 1) //平多 54 | { 55 | if(K1 < D1) 56 | { 57 | sell(lots,open);//<--这里用的是sell(lots,close); 58 | Return; 59 | } 60 | } 61 | //止损 62 | If(MarketPosition == 1) 63 | { 64 | If(Low < EntryPrice - StopLoss * MinMove*PriceScale) 65 | { 66 | myExitPrice = EntryPrice - (StopLoss+1) * MinMove*PriceScale; 67 | myExitPrice = max(low,myExitPrice); 68 | Sell(lots,myExitPrice); 69 | } 70 | } 71 | Else If(MarketPosition == -1) 72 | { 73 | If(High > EntryPrice + StopLoss * MinMove*PriceScale) 74 | { 75 | myExitPrice = EntryPrice + (StopLoss+1) * MinMove*PriceScale; 76 | myExitPrice = min(high,myExitPrice); 77 | BuyToCover(lots,myExitPrice); 78 | } 79 | } 80 | } 81 | end -------------------------------------------------------------------------------- /strats/飞天创富系统策略.txt: -------------------------------------------------------------------------------- 1 | 开拓者飞天创富系统策略源码 2 | 3 | (一)思路:1.同时交易四个品种,每个品种动用总资金的10%。 4 | 2.以连续合约发出信号,交易主力合约,连续合约为data0,现主力合约为data1,下一个主力合约为data2; 5 | 3.总资金以A_CurrentEquity 表达是否正确; 6 | 4.盘中达到止损,立即以止损价止损; 7 | 5.开盘跳空越过止损价,立即以开盘价止损,但不能因集合竞价出现废单; 8 | 9 | (二)程序代码: 10 | 11 | //------------------------------------------------------------------------ 12 | // 简称: FTCF 13 | // 名称: 飞天创富 14 | // 类别: 公式应用 15 | // 类型: 用户应用 16 | //------------------------------------------------------------------------ 17 | 18 | Params 19 | Numeric m(7); 20 | numeric P(1.5); 21 | numeric n(0.1); 22 | Vars 23 | NumericSeries a; 24 | NumericSeries b; 25 | NumericSeries e; 26 | numeric entrylots; 27 | NumericSeries dtzf; 28 | NumericSeries ktdf; 29 | Begin 30 | a=(3*c+l+o+h)/6; 31 | b=(20*a+19*a[1]+18*a[2]+17*a[3]+16*a[4]+15*a[5]+14*a[6]+13*a[7]+12*a[8]+11*a[9]+10*a[10]+9*a[11]+8*a[12]+7*a[13]+6*a[14]+5*a[15]+4*a[16]+3*a[17]+2*a[18]+a[20])/210;//来源 www.cxh99.com 32 | e=average(b,m); 33 | dtzf=c/Close[NthCon(CrossOver(b,e),1)]-1; 34 | ktdf=1-c/Close[NthCon(CrossOver(e,b),1)]; 35 | 36 | //多头开仓 37 | if(crossover(b,e) and MarketPosition!=1 and ktdfdata2.v and CurrentTime>=0.145955) 38 | { 39 | entryLots= (A_CurrentEquity *0.1)/(data1.C*ContractUnit*MarginRatio); 40 | entryLots = IntPart(entryLots ); 41 | data1.Buy(entryLots,data1.C); 42 | } 43 | if(crossover(b,e) and MarketPosition!=1 AND ktdf>=n and data1.v>data2.v and CurrentTime>=0.145955) 44 | { 45 | entryLots= (A_CurrentEquity*0.05)/(data1.C*ContractUnit*MarginRatio); 46 | entryLots = IntPart(entryLots ); 47 | data1.Buy(entryLots,data1.C); 48 | } 49 | if(crossover(b,e) and MarketPosition!=1 and ktdf=0.145955) 50 | { 51 | entryLots= (A_CurrentEquity *0.1)/(data2.C*ContractUnit*MarginRatio); 52 | entryLots = IntPart(entryLots ); 53 | data1.BuyToCover(0,data1.c); 54 | data2.Buy(entryLots,data2.C); 55 | } 56 | if(crossover(b,e) and MarketPosition!=1 AND ktdf>=n and data1.v=0.145955) 57 | { 58 | entryLots= (A_CurrentEquity *0.05)/(data2.C*ContractUnit*MarginRatio); 59 | entryLots = IntPart(entryLots ); 60 | data1.BuyToCover(0,data1.c); 61 | data2.Buy(entryLots,data2.C); 62 | } 63 | //多头开仓结束 64 | 65 | //空头开仓 66 | if(Crossover(e,b) and MarketPosition!=(-1) and dtzfdata2.v and CurrentTime>=0.145955) 67 | { 68 | entryLots= (A_CurrentEquity * 0.1)/(data1.C*ContractUnit*MarginRatio); 69 | entryLots = IntPart(entryLots ); 70 | data1.SellShort(entryLots,data1.c); 71 | }//来源 www.chengxuhuajiaoyi.com 72 | if(Crossover(e,b) and MarketPosition!=(-1) and dtzf>=n and data1.v>data2.v and CurrentTime>=0.145955) 73 | { 74 | entryLots= (A_CurrentEquity* 0.05)/(data1.C*ContractUnit*MarginRatio); 75 | entryLots = IntPart(entryLots ); 76 | data1.Sellshort(entryLots,data1.c); 77 | } 78 | if(Crossover(e,b) and MarketPosition!=(-1) and dtzf=0.145955) 79 | { 80 | entryLots= (A_CurrentEquity * 0.1)/(data2.C*ContractUnit*MarginRatio); 81 | entryLots = IntPart(entryLots ); 82 | data1.Sell(0,data1.c); 83 | data2.SellShort(entryLots,data2.c); 84 | } 85 | if(Crossover(e,b) and MarketPosition!=(-1) and dtzf>=n and data1.v=0.145955) 86 | { 87 | entryLots= (A_CurrentEquity * 0.05)/(data2.C*ContractUnit*MarginRatio); 88 | entryLots = IntPart(entryLots ); 89 | data1.Sell(0,data1.c); 90 | data2.Sellshort(entryLots,data2.c); 91 | } 92 | //空头开仓结束 93 | 94 | //多头止损 95 | If(marketposition==1 and data1.l<=A_BuyAvgPrice*(1-p/100) and date>lastEntryDate AND currenttime>0.090000) 96 | { 97 | data1.Sell(0,A_BuyAvgPrice*(1-p/100)); 98 | } 99 | If(marketposition==1 and data1.o<=A_BuyAvgPrice*(1-p/100) and date>lastEntryDate AND currenttime>0.090000) 100 | { 101 | data1.Sell(0,o); 102 | } 103 | //多头止损结束 104 | 105 | //空头止损 106 | If(marketposition==(-1) and data1.h>=A_sellAvgPrice*(1+p/100) and date>lastEntryDate AND currenttime>0.090000) 107 | { 108 | data1.BuyToCover(0,A_sellAvgPrice*(1+p/100)); 109 | } 110 | If(marketposition==(-1) and data1.o>=A_sellAvgPrice*(1+p/100) and date>lastEntryDate AND currenttime>0.090000) 111 | { 112 | data1.BuyToCover(0,o); 113 | } 114 | //空头止损结束 115 | 116 | End -------------------------------------------------------------------------------- /test_data.py: -------------------------------------------------------------------------------- 1 | import data_saver 2 | import tushare as ts 3 | import datetime 4 | import pandas as pd 5 | import mysql.connector as mysqlconn 6 | import misc 7 | import os 8 | import urllib2 9 | import pytz 10 | import patoolib 11 | import mysqlaccess as db 12 | from glob import glob 13 | 14 | from bs4 import BeautifulSoup 15 | from datetime import datetime 16 | from pandas.io.data import DataReader 17 | 18 | SITE = "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies" 19 | START = datetime(1900, 1, 1, 0, 0, 0, 0, pytz.utc) 20 | END = datetime.today().utcnow() 21 | 22 | 23 | def scrape_list(site): 24 | hdr = {'User-Agent': 'Mozilla/5.0'} 25 | req = urllib2.Request(site, headers=hdr) 26 | page = urllib2.urlopen(req) 27 | soup = BeautifulSoup(page) 28 | 29 | table = soup.find('table', {'class': 'wikitable sortable'}) 30 | sector_tickers = dict() 31 | for row in table.findAll('tr'): 32 | col = row.findAll('td') 33 | if len(col) > 0: 34 | sector = str(col[3].string.strip()).lower().replace(' ', '_') 35 | ticker = str(col[0].string.strip()) 36 | if sector not in sector_tickers: 37 | sector_tickers[sector] = list() 38 | sector_tickers[sector].append(ticker) 39 | return sector_tickers 40 | 41 | 42 | def download_ohlc(sector_tickers, start, end): 43 | sector_ohlc = {} 44 | for sector, tickers in sector_tickers.iteritems(): 45 | print 'Downloading data from Yahoo for %s sector' % sector 46 | data = DataReader(tickers, 'yahoo', start, end) 47 | for item in ['Open', 'High', 'Low']: 48 | data[item] = data[item] * data['Adj Close'] / data['Close'] 49 | data.rename(items={'Open': 'open', 'High': 'high', 'Low': 'low', 50 | 'Adj Close': 'close', 'Volume': 'volume'}, 51 | inplace=True) 52 | data.drop(['Close'], inplace=True) 53 | sector_ohlc[sector] = data 54 | print 'Finished downloading data' 55 | return sector_ohlc 56 | 57 | 58 | def store_HDF5(sector_ohlc, path): 59 | with pd.get_store(path) as store: 60 | for sector, ohlc in sector_ohlc.iteritems(): 61 | store[sector] = ohlc 62 | 63 | 64 | def get_snp500(): 65 | sector_tickers = scrape_list(SITE) 66 | sector_ohlc = download_ohlc(sector_tickers, START, END) 67 | store_HDF5(sector_ohlc, 'snp500.h5') 68 | 69 | def save_tick_data(tday, folder = '', tick_id = 300000): 70 | all_insts = data_saver.filter_main_cont(tday) 71 | cnx = mysql.connector.connect(**misc.mysqlaccess.dbconfig) 72 | for inst in all_insts: 73 | stmt = "select * from fut_tick where instID='{prod}' and date='{cdate}' and tick_id>='{tick}'".format(prod=inst, cdate=tday.strftime('%Y-%m-%d'), tick = tick_id) 74 | df = pd.io.sql.read_sql(stmt, cnx) 75 | df.to_csv(folder + inst + '.csv', header=False, index=False) 76 | return 77 | 78 | def load_tick_data(tday, folder = ''): 79 | all_insts = data_saver.filter_main_cont(tday) 80 | cnx = mysql.connector.connect(**misc.mysqlaccess.dbconfig) 81 | cursor = cnx.cursor() 82 | for inst in all_insts: 83 | data_file = folder + inst + '.csv' 84 | if os.path.isfile(data_file): 85 | stmt = "load data local infile '{data_file}' replace into table fut_tick fields terminated by ',';".format(data_file = data_file) 86 | cursor.execute( stmt ) 87 | cnx.commit() 88 | print inst 89 | cnx.close() 90 | return 91 | 92 | def import_datayes_daily_data(start_date, end_date, cont_list = [], is_replace = False): 93 | numdays = (end_date - start_date).days + 1 94 | date_list = [start_date + datetime.timedelta(days=x) for x in range(0, numdays) ] 95 | date_list = [ d for d in date_list if (d.weekday()< 5) and (d not in misc.CHN_Holidays)] 96 | for d in date_list: 97 | cnt = 0 98 | dstring = d.strftime('%Y%m%d') 99 | ts.set_token(misc.datayes_token) 100 | mkt = ts.Market() 101 | df = mkt.MktFutd(tradeDate = dstring) 102 | if len(df.ticker) == 0: 103 | continue 104 | for cont in df.ticker: 105 | if (len(cont_list) > 0) and (cont not in cont_list): 106 | continue 107 | data = df[df.ticker==cont] 108 | if len(data) == 0: 109 | print 'no data for %s for %s' % (cont, dstring) 110 | else: 111 | data_dict = {} 112 | data_dict['date'] = d 113 | data_dict['open'] = float(data.openPrice) 114 | data_dict['close'] = float(data.closePrice) 115 | data_dict['high'] = float(data.highestPrice) 116 | data_dict['low'] = float(data.lowestPrice) 117 | data_dict['volume'] = int(data.turnoverVol) 118 | data_dict['openInterest'] = int(data.openInt) 119 | if data_dict['volume'] > 0: 120 | cnt += 1 121 | db.insert_daily_data(cont, data_dict, is_replace = is_replace, dbtable = 'fut_daily') 122 | print 'date=%s, insert count = %s' % (d, cnt) 123 | 124 | def extract_rar_data(source, target, extract_src = False): 125 | if extract_src: 126 | for file in os.listdir(source): 127 | if file.endswith(".rar"): 128 | patoolib.extract_archive(source+file, outdir = target) 129 | allrar = [y for x in os.walk(target) for y in glob(os.path.join(x[0], '*.rar'))] 130 | for file in allrar: 131 | patoolib.extract_archive(file, outdir = target) 132 | 133 | def load_csv_tick(target, db_table = 'test_fut_tick'): 134 | cnx = mysqlconn.connect(**db.dbconfig) 135 | allcsvs = [y for x in os.walk(target) for y in glob(os.path.join(x[0], '*.csv'))] 136 | for csvfile in allcsvs: 137 | try: 138 | df = pd.DataFrame() 139 | df = pd.read_csv(csvfile, header = None, index_col = False, skiprows = 1, usecols = [1, 2, 3, 4, 7, 12, 13, 14,15 ]) 140 | df.columns = ['instID', 'datetime','price', 'openInterest', 'volume', 'bidPrice1', 'askPrice1', 'bidVol1', 'askVol1'] 141 | df['datetime'] = pd.to_datetime(df.datetime) 142 | df['date'] = df.datetime.apply(lambda x:x.date()) 143 | df['hour'] = df.datetime.apply(lambda x:x.hour) 144 | df['min'] = df.datetime.apply(lambda x:x.minute) 145 | df['sec'] = df.datetime.apply(lambda x:x.second) 146 | df['msec'] = df.datetime.apply(lambda x:x.microsecond)/1000 147 | df['tick_id'] = ((df['hour'] + 6) % 24)*100000 + df['min']*1000 + df['sec']*10 + df['msec']/100 148 | del df['datetime'] 149 | print csvfile, len(df) 150 | df.to_sql(name = db_table, flavor = 'mysql', con = cnx, if_exists='append') 151 | cnx.commit() 152 | except: 153 | continue 154 | cnx.close() 155 | return 0 156 | 157 | if __name__ == '__main__': 158 | print 159 | -------------------------------------------------------------------------------- /tools/candle_graph_demo.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY 3 | from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc 4 | 5 | def show_candlestick(ticker, startD, endD): 6 | mondays = WeekdayLocator(MONDAY) # major ticks on the mondays 7 | alldays = DayLocator() # minor ticks on the days 8 | weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 9 | dayFormatter = DateFormatter('%d') # e.g., 12 10 | 11 | quotes = quotes_historical_yahoo_ohlc(ticker, startD, endD) 12 | if len(quotes) == 0: 13 | raise SystemExit 14 | 15 | fig, ax = plt.subplots() 16 | fig.subplots_adjust(bottom=0.2) 17 | #ax.xaxis.set_major_locator(mondays) 18 | #ax.xaxis.set_minor_locator(alldays) 19 | #ax.xaxis.set_major_formatter(weekFormatter) 20 | #ax.xaxis.set_minor_formatter(dayFormatter) 21 | 22 | #plot_day_summary(ax, quotes, ticksize=3) 23 | candlestick_ohlc(ax, quotes, width=0.6) 24 | 25 | ax.xaxis_date() 26 | ax.autoscale_view() 27 | plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') 28 | 29 | plt.show() -------------------------------------------------------------------------------- /tools/chart.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import numpy as np 3 | from matplotlib import verbose, get_cachedir 4 | from matplotlib.dates import date2num 5 | from matplotlib.cbook import iterable, mkdirs 6 | from matplotlib.collections import LineCollection, PolyCollection 7 | from matplotlib.colors import colorConverter 8 | from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT 9 | from matplotlib.patches import Rectangle 10 | from matplotlib.transforms import Affine2D 11 | 12 | def cchart(ax, ohlc_df, width=4, 13 | colorup='k', colordown='r', 14 | alpha=0.75, 15 | ): 16 | """ 17 | Represent the open, close as a bar line and high low range as a 18 | vertical line. 19 | ax : an Axes instance to plot to 20 | width : the bar width in points 21 | colorup : the color of the lines where close >= open 22 | colordown : the color of the lines where close < open 23 | alpha : bar transparency 24 | 25 | return value is lineCollection, barCollection 26 | """ 27 | 28 | # note this code assumes if any value open, close, low, high is 29 | # missing they all are missing 30 | 31 | delta = width/2. 32 | barVerts = [ ( (i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open) ) for i, open, close in zip(xrange(len(ohlc_df.open)), ohlc_df.open, ohlc_df.close) if open != -1 and close!=-1 ] 33 | 34 | #rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(ohlc_df.low)), ohlc_df.low, ohlc_df.high) if low != -1 ] 35 | rangeSegments = [ ((i, max(open, close)), (i, high)) for i, high, open, close in zip(xrange(len(ohlc_df.high)), ohlc_df.high, ohlc_df.open, ohlc_df.close) if high!=-1 ] 36 | rangeSegments2 = [ ((i, low), (i, min(open, close))) for i, low, open, close in zip(xrange(len(ohlc_df.low)), ohlc_df.low, ohlc_df.open, ohlc_df.close) if low!=-1] 37 | 38 | r,g,b = colorConverter.to_rgb(colorup) 39 | colorup = r,g,b,alpha 40 | r,g,b = colorConverter.to_rgb(colordown) 41 | colordown = r,g,b,alpha 42 | colord = { True : colorup, 43 | False : colordown, 44 | } 45 | colors = [colord[open AB CD E" 5 | iterable = iter(iterable) 6 | while True: 7 | # store one line in memory, 8 | # chain it to an iterator on the rest of the chunk 9 | yield chain([next(iterable)], islice(iterable, n-1)) 10 | 11 | def split(file_large, file_size): 12 | l = file_size*(10**3) 13 | with open(file_large) as bigfile: 14 | for i, lines in enumerate(chunks(bigfile, l)): 15 | file_split = '{}.{}'.format(file_large, i) 16 | with open(file_split, 'w') as f: 17 | f.writelines(lines) -------------------------------------------------------------------------------- /tools/test_chart.py: -------------------------------------------------------------------------------- 1 | import matplotlib 2 | matplotlib.use('TkAgg') 3 | import pandas as pd 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | from matplotlib.finance import candlestick 7 | from matplotlib.finance import candlestick2 8 | import chart 9 | import mysqlaccess as db 10 | import datetime 11 | 12 | d_start = datetime.date(2015,1,2) 13 | d_end = datetime.date(2015,4,24) 14 | dbtable = 'fut_daily' 15 | inst = 'm1509' 16 | df = db.load_daily_data_to_df(dbtable, inst, d_start, d_end) 17 | ohlc = pd.DataFrame(df) 18 | ohlc = ohlc.drop(u'openInterest', 1) 19 | ohlc = ohlc.drop('volume', 1) 20 | ohlc['sn'] = range(len(ohlc.index)) 21 | ohlc = ohlc.set_index('sn') 22 | fig = plt.figure() 23 | ax = fig.add_subplot(311) 24 | y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) 25 | ax.yaxis.set_major_formatter(y_formatter) 26 | chart.cchart(ax, ohlc, width=.5, colorup='g', colordown='r', alpha=1) 27 | ohlc['close'].plot(ax=ax) 28 | ay = fig.add_subplot(312) 29 | ohlc.plot(ax=ay) 30 | #ax.set_xticks(np.arange(0,len(ohlc.index),5)) 31 | #plt.savefig("1.png") 32 | plt.show() 33 | -------------------------------------------------------------------------------- /tools/yahoo_mysql_importer.py: -------------------------------------------------------------------------------- 1 | from time import sleep, strftime, localtime 2 | from Tkinter import * 3 | #import MySQLdb 4 | import mysql.connector 5 | import urllib 6 | import csv 7 | import string 8 | 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | 14 | frame = Frame(master) 15 | frame.pack() 16 | 17 | self.mysqlinfo_label = Label(frame, text='MySQL fields:') 18 | self.mysqlinfo_label.grid(row=0) 19 | 20 | self.label_host = Label(frame, text='Host:') 21 | self.label_host.grid(row=1) 22 | 23 | host_text = StringVar() 24 | host_text.set("127.0.0.1") 25 | 26 | self.entry_host = Entry(frame, textvariable=host_text) 27 | self.entry_host.grid(row=1, column=1) 28 | 29 | self.label_user = Label(frame, text='User:') 30 | self.label_user.grid(row=2) 31 | 32 | user_text = StringVar() 33 | user_text.set("root") 34 | 35 | self.entry_user = Entry(frame, textvariable=user_text) 36 | self.entry_user.grid(row=2, column=1) 37 | 38 | self.label_password = Label(frame, text='Password:') 39 | self.label_password.grid(row=3) 40 | 41 | self.entry_password = Entry(frame, show="*") 42 | self.entry_password.grid(row=3, column=1) 43 | 44 | self.label_database = Label(frame, text='Database:') 45 | self.label_database.grid(row=4) 46 | 47 | database_text = StringVar() 48 | database_text.set("stocks") 49 | 50 | self.entry_database = Entry(frame, textvariable=database_text) 51 | self.entry_database.grid(row=4, column=1) 52 | 53 | self.label_empty = Label(frame, text='') 54 | self.label_empty.grid(row=5) 55 | 56 | self.label_twscontractinfo = Label(frame, text='Yahoo info:') 57 | self.label_twscontractinfo.grid(row=9) 58 | 59 | self.label_symbol = Label(frame, text='Symbol:') 60 | self.label_symbol.grid(row=10) 61 | 62 | self.entry_symbol = Entry(frame) 63 | self.entry_symbol.grid(row=10, column=1) 64 | 65 | self.label_startmonth = Label(frame, text='Start Month:') 66 | self.label_startmonth.grid(row=11) 67 | 68 | self.entry_startmonth = Entry(frame) 69 | self.entry_startmonth.grid(row=11, column=1) 70 | 71 | self.label_startday = Label(frame, text='Start Day') 72 | self.label_startday.grid(row=12) 73 | 74 | self.entry_startday = Entry(frame) 75 | self.entry_startday.grid(row=12, column=1) 76 | 77 | self.label_startyear = Label(frame, text='Start Year:') 78 | self.label_startyear.grid(row=13) 79 | 80 | self.entry_startyear = Entry(frame) 81 | self.entry_startyear.grid(row=13, column=1) 82 | 83 | self.label_empty = Label(frame, text='') 84 | self.label_empty.grid(row=14) 85 | 86 | self.button_download = Button(frame, text="Download", command=self.tws_connect) 87 | self.button_download.grid(row=15, column=1) 88 | 89 | self.button_import = Button(frame, text="Import", command=self.mysql_connect) 90 | self.button_import.grid(row=16, column=1) 91 | 92 | self.label_empty = Label(frame, text='') 93 | self.label_empty.grid(row=17) 94 | 95 | 96 | def tws_connect(self): 97 | print "downloading csv file from yahoo..." 98 | 99 | #split symbol string 100 | 101 | #raw_symbol_input = "%s" % (str(self.entry_symbol.get())) 102 | new_symbolinput = string.split(self.entry_symbol.get(), ',') 103 | 104 | #print raw_symbol_input 105 | print new_symbolinput 106 | 107 | for i in new_symbolinput: 108 | print i 109 | 110 | for i in new_symbolinput: 111 | print "downloading..." + i 112 | webFile = urllib.urlopen("http://ichart.finance.yahoo.com/table.csv?s=" + i + "&a=" + self.entry_startmonth.get() + '&b=' + self.entry_startday.get() + "&c=" + self.entry_startyear.get()) 113 | fileName = i + ".csv" 114 | localFile = open(fileName.split('/')[-1], 'w') 115 | localFile.write(webFile.read()) 116 | webFile.close() 117 | localFile.close() 118 | 119 | fieldnames = ['Symbol', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close'] 120 | fileName2 = "csv/" + i + "2.csv" 121 | with open(fileName, 'rb') as csvinput: 122 | with open(fileName2, 'wb') as csvoutput: 123 | csvwriter = csv.DictWriter(csvoutput, fieldnames, delimiter=',') 124 | csvwriter.writeheader() 125 | for row in csv.DictReader(csvinput): 126 | row['Symbol'] = i 127 | csvwriter.writerow(row) 128 | 129 | 130 | def mysql_connect(self): 131 | print "connecting to mysql..." 132 | 133 | print "MySQL host: " + self.entry_host.get() 134 | print "MySQL user: " + self.entry_user.get() 135 | print "MySQL database: " + self.entry_database.get() 136 | 137 | db = mysql.connector.connect(host=self.entry_host.get(), user=self.entry_user.get(),passwd=self.entry_password.get(), db=self.entry_database.get()) 138 | cur = db.cursor() 139 | 140 | #split symbol string 141 | 142 | #raw_symbol_input = "%s" % (str(self.entry_symbol.get())) 143 | new_symbolinput2 = string.split(self.entry_symbol.get(), ',') 144 | 145 | for i in new_symbolinput2: 146 | 147 | cur.execute("load data local infile 'C://Users//ryan//Desktop//market//yahoo_import_v0.1 - Copy//csv//" + i + "2.csv' into table `stocks`.`stocks_yahoo_prev` fields terminated by ',' lines terminated by '\n' ignore 1 lines (`symbol`,`date`,`open`,`high`,`low`,`close`,`volume`,`adj_close`);") 148 | db.commit() 149 | 150 | print "contract info..." 151 | print "Symbol: " + i 152 | 153 | root = Tk() 154 | root.title('Historical Data: Download and Import') 155 | app = App(root) 156 | 157 | root.mainloop() -------------------------------------------------------------------------------- /yahoo_mysql_importer.py: -------------------------------------------------------------------------------- 1 | from time import sleep, strftime, localtime 2 | from Tkinter import * 3 | #import MySQLdb 4 | import mysql.connector 5 | import urllib 6 | import csv 7 | import string 8 | 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | 14 | frame = Frame(master) 15 | frame.pack() 16 | 17 | self.mysqlinfo_label = Label(frame, text='MySQL fields:') 18 | self.mysqlinfo_label.grid(row=0) 19 | 20 | self.label_host = Label(frame, text='Host:') 21 | self.label_host.grid(row=1) 22 | 23 | host_text = StringVar() 24 | host_text.set("127.0.0.1") 25 | 26 | self.entry_host = Entry(frame, textvariable=host_text) 27 | self.entry_host.grid(row=1, column=1) 28 | 29 | self.label_user = Label(frame, text='User:') 30 | self.label_user.grid(row=2) 31 | 32 | user_text = StringVar() 33 | user_text.set("root") 34 | 35 | self.entry_user = Entry(frame, textvariable=user_text) 36 | self.entry_user.grid(row=2, column=1) 37 | 38 | self.label_password = Label(frame, text='Password:') 39 | self.label_password.grid(row=3) 40 | 41 | self.entry_password = Entry(frame, show="*") 42 | self.entry_password.grid(row=3, column=1) 43 | 44 | self.label_database = Label(frame, text='Database:') 45 | self.label_database.grid(row=4) 46 | 47 | database_text = StringVar() 48 | database_text.set("stocks") 49 | 50 | self.entry_database = Entry(frame, textvariable=database_text) 51 | self.entry_database.grid(row=4, column=1) 52 | 53 | self.label_empty = Label(frame, text='') 54 | self.label_empty.grid(row=5) 55 | 56 | self.label_twscontractinfo = Label(frame, text='Yahoo info:') 57 | self.label_twscontractinfo.grid(row=9) 58 | 59 | self.label_symbol = Label(frame, text='Symbol:') 60 | self.label_symbol.grid(row=10) 61 | 62 | self.entry_symbol = Entry(frame) 63 | self.entry_symbol.grid(row=10, column=1) 64 | 65 | self.label_startmonth = Label(frame, text='Start Month:') 66 | self.label_startmonth.grid(row=11) 67 | 68 | self.entry_startmonth = Entry(frame) 69 | self.entry_startmonth.grid(row=11, column=1) 70 | 71 | self.label_startday = Label(frame, text='Start Day') 72 | self.label_startday.grid(row=12) 73 | 74 | self.entry_startday = Entry(frame) 75 | self.entry_startday.grid(row=12, column=1) 76 | 77 | self.label_startyear = Label(frame, text='Start Year:') 78 | self.label_startyear.grid(row=13) 79 | 80 | self.entry_startyear = Entry(frame) 81 | self.entry_startyear.grid(row=13, column=1) 82 | 83 | self.label_empty = Label(frame, text='') 84 | self.label_empty.grid(row=14) 85 | 86 | self.button_download = Button(frame, text="Download", command=self.tws_connect) 87 | self.button_download.grid(row=15, column=1) 88 | 89 | self.button_import = Button(frame, text="Import", command=self.mysql_connect) 90 | self.button_import.grid(row=16, column=1) 91 | 92 | self.label_empty = Label(frame, text='') 93 | self.label_empty.grid(row=17) 94 | 95 | 96 | def tws_connect(self): 97 | print "downloading csv file from yahoo..." 98 | 99 | #split symbol string 100 | 101 | #raw_symbol_input = "%s" % (str(self.entry_symbol.get())) 102 | new_symbolinput = string.split(self.entry_symbol.get(), ',') 103 | 104 | #print raw_symbol_input 105 | print new_symbolinput 106 | 107 | for i in new_symbolinput: 108 | print i 109 | 110 | for i in new_symbolinput: 111 | print "downloading..." + i 112 | webFile = urllib.urlopen("http://ichart.finance.yahoo.com/table.csv?s=" + i + "&a=" + self.entry_startmonth.get() + '&b=' + self.entry_startday.get() + "&c=" + self.entry_startyear.get()) 113 | fileName = i + ".csv" 114 | localFile = open(fileName.split('/')[-1], 'w') 115 | localFile.write(webFile.read()) 116 | webFile.close() 117 | localFile.close() 118 | 119 | fieldnames = ['Symbol', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close'] 120 | fileName2 = "csv/" + i + "2.csv" 121 | with open(fileName, 'rb') as csvinput: 122 | with open(fileName2, 'wb') as csvoutput: 123 | csvwriter = csv.DictWriter(csvoutput, fieldnames, delimiter=',') 124 | csvwriter.writeheader() 125 | for row in csv.DictReader(csvinput): 126 | row['Symbol'] = i 127 | csvwriter.writerow(row) 128 | 129 | 130 | def mysql_connect(self): 131 | print "connecting to mysql..." 132 | 133 | print "MySQL host: " + self.entry_host.get() 134 | print "MySQL user: " + self.entry_user.get() 135 | print "MySQL database: " + self.entry_database.get() 136 | 137 | db = mysql.connector.connect(host=self.entry_host.get(), user=self.entry_user.get(),passwd=self.entry_password.get(), db=self.entry_database.get()) 138 | cur = db.cursor() 139 | 140 | #split symbol string 141 | 142 | #raw_symbol_input = "%s" % (str(self.entry_symbol.get())) 143 | new_symbolinput2 = string.split(self.entry_symbol.get(), ',') 144 | 145 | for i in new_symbolinput2: 146 | 147 | cur.execute("load data local infile 'C://Users//ryan//Desktop//market//yahoo_import_v0.1 - Copy//csv//" + i + "2.csv' into table `stocks`.`stocks_yahoo_prev` fields terminated by ',' lines terminated by '\n' ignore 1 lines (`symbol`,`date`,`open`,`high`,`low`,`close`,`volume`,`adj_close`);") 148 | db.commit() 149 | 150 | print "contract info..." 151 | print "Symbol: " + i 152 | 153 | root = Tk() 154 | root.title('Historical Data: Download and Import') 155 | app = App(root) 156 | 157 | root.mainloop() --------------------------------------------------------------------------------