Пример #1
0
def main():
    theMarket = Market(
        data_path="data/%s_Candlestick_4_Hour_BID_01.08.2018-30.11.2018.csv" %
        CURRENCY_PAIR)  #, indicators={'ADX': 12})
    MyRecord = Record()
    MyOrderManager = OrderManager(market=theMarket, record=MyRecord)
    MyTrader = SureFireTrader(orderManager=MyOrderManager)

    SLTP_pips = [20, 25, 30]
    start_order_type = ['BUY', 'SELL']
    max_level_limit = [2, 3, 4]
    window_size = 12

    # Create a RL agent
    agent = ConstantAgent(
        states=dict(type='float', shape=(window_size, window_size,
                                         4)),  #[Open, High, Low, Close]
        actions=dict(
            SLTP_pips=dict(type='int',
                           num_actions=len(SLTP_pips)),  #[20,25,30]
            start_order_type=dict(
                type='int',
                num_actions=len(start_order_type)),  #['BUY','SELL']
            max_level_limit=dict(type='int',
                                 num_actions=len(max_level_limit))  #[2,3,4]
        ),
        action_values={
            'SLTP_pips': 0,
            'max_level_limit': 0,
            'start_order_type': 0
        })
    if not os.path.exists("save_model/constant/trades"):
        os.makedirs("save_model/constant/trades")
    if not os.path.exists('save_model/constant/0000'):
        os.makedirs('save_model/constant/0000')
    agent.save_model('save_model/constant/0000/model')

    reward_history = []

    profit_history = []
    this_reward_history = []
    idle_count = 0
    round_count = 0
    episode_end = False
    max_idle_limit = 12  #future action
    MyRecord.reset()
    MyOrderManager.reset()
    theMarket.reset(start_index=window_size)

    pbar = tqdm()
    while (theMarket.next()):  #main loop, essential

        pbar.update(1)  # simple-GUI

        ################### ROUTINES ###################
        MyOrderManager.orders_check()  #routine, after market.next
        trade_status, other_detail = MyTrader.status_check(
        )  #routine, after orders_check
        ################################################

        ################### GET STATE ##################
        ohlc = theMarket.get_ohlc(size=window_size)
        indicators = theMarket.get_indicators(size=window_size)
        O, H, L, C = gaf_encode(ohlc['Open']), gaf_encode(ohlc['High']), \
                        gaf_encode(ohlc['Low']),gaf_encode(ohlc['Close'])
        #ADX = gaf_encode(indicators['ADX'])
        state = np.stack((O, H, L, C), axis=-1)
        ################################################

        ################## TAKE ACTION #################
        if trade_status == 'TRADE_OVER':

            ############ GET REWARD & TRAIN ################
            if theMarket.get_current_index() > window_size:
                '''
                profit = sum(round(order['profit'],5) for order in other_detail if order['profit']>0)
                loss = sum(round(order['profit'],5) for order in other_detail if order['profit']<0)
                
                this_profit_factor = MyRecord.get_profit_factor()
                this_trade_length = len(MyRecord.get_history())
                reward = this_profit_factor*np.sqrt(this_trade_length)#SQN
                '''
                raw_reward = (MyRecord.get_net_profit() -
                              profit_history[-1]) / theMarket.get_pip()
                penalty = 1.0 - 0.1 * len(other_detail)
                if raw_reward > 0:
                    reward = raw_reward * penalty
                else:
                    if len(other_detail) == 0:
                        reward = 0
                    else:
                        reward = -np.abs(
                            other_detail[0]['TP'] -
                            other_detail[0]['price']) / theMarket.get_pip()

                if theMarket.get_current_index() >= theMarket.get_data_length(
                ) - max_idle_limit * max_level_limit[-1]:
                    episode_end = True
                agent.observe(
                    reward=reward, terminal=episode_end
                )  # Add experience, agent automatically updates model according to batch size
                this_reward_history.append(reward)
                if episode_end == True:
                    pbar.close()
                    reward_history.append(this_reward_history)
                    break
            action = agent.act(state)  # Get prediction from agent, execute
            SL_pip = SLTP_pips[action['SLTP_pips']] * 2
            TP_pip = SLTP_pips[action['SLTP_pips']]
            MyTrader.set_max_level(max_level_limit[action['max_level_limit']])
            first_order_type = start_order_type[action['start_order_type']]
            ################################################

            MyTrader.new_trade(SL_pip=SL_pip,
                               TP_pip=TP_pip,
                               start_order_type=first_order_type)

            round_count += 1
            idle_count = 0
            logging.info(
                "NewTradeStarted: current net profit=%f (price@%f)" %
                (MyRecord.get_net_profit(), theMarket.get_market_price()))

        elif trade_status == 'ADD_ORDER':
            last_order = MyTrader.get_orders_detail()[-1]
            if last_order['order_type'] == 'BUY':
                price = last_order['price'] - theMarket.get_pip(TP_pip)
            elif last_order['order_type'] == 'SELL':
                price = last_order['price'] + theMarket.get_pip(TP_pip)
            MyTrader.add_reverse_order(price=price,
                                       SL_pip=SL_pip,
                                       TP_pip=TP_pip)
            idle_count = 0

        elif trade_status == 'ERROR':
            logging.warning("SureFireError: order issues...")

        elif trade_status == 'NONE':
            idle_count += 1
            if idle_count >= max_idle_limit:

                ############ GET REWARD & TRAIN ################
                '''
                profit = sum(round(order['profit'],5) for order in other_detail if order['profit']>0)
                loss = sum(round(order['profit'],5) for order in other_detail if order['profit']<0)
                
                this_profit_factor = MyRecord.get_profit_factor()
                this_trade_length = len(MyRecord.get_history())
                reward = this_profit_factor*np.sqrt(this_trade_length)#SQN
                '''
                raw_reward = (MyRecord.get_net_profit() -
                              profit_history[-1]) / theMarket.get_pip()
                penalty = 1.0 - 0.1 * len(other_detail)
                if raw_reward > 0:
                    reward = raw_reward * penalty
                else:
                    if len(other_detail) == 0:
                        reward = 0
                    else:
                        reward = -np.abs(
                            other_detail[0]['TP'] -
                            other_detail[0]['price']) / theMarket.get_pip()

                if theMarket.get_current_index() >= theMarket.get_data_length(
                ) - max_idle_limit * max_level_limit[-1]:
                    episode_end = True
                agent.observe(
                    reward=reward, terminal=episode_end
                )  # Add experience, agent automatically updates model according to batch size
                this_reward_history.append(reward)
                if episode_end == True:
                    pbar.close()
                    reward_history.append(this_reward_history)
                    break

                action = agent.act(state)  # Get prediction from agent, execute
                SL_pip = SLTP_pips[action['SLTP_pips']] * 2
                TP_pip = SLTP_pips[action['SLTP_pips']]
                MyTrader.set_max_level(
                    max_level_limit[action['max_level_limit']])
                first_order_type = start_order_type[action['start_order_type']]
                ################################################

                MyTrader.new_trade(SL_pip=SL_pip,
                                   TP_pip=TP_pip,
                                   start_order_type=first_order_type)
                idle_count = 0
                logging.info(
                    "NewTradeStarted: current net profit=%f (price@%f)" %
                    (MyRecord.get_net_profit(), theMarket.get_market_price()))
        ################################################

        profit_history.append(MyRecord.get_net_profit())  #for plotting

        #MyRecord.show_details()
        #print("Rounds of Tradings: %d\n"%round_count)

    with open('save_model/constant/trades/episode_0000.pkl', 'wb') as f:
        pickle.dump(MyRecord.get_history(), f, protocol=-1)

    with open('save_model/constant/trades/profit_history.pkl', 'wb') as f:
        pickle.dump(profit_history, f, protocol=-1)

    with open('save_model/constant/trades/reward_history.pkl', 'wb') as f:
        pickle.dump(reward_history, f, protocol=-1)

    MyRecord.show_details()
Пример #2
0
def main():
    PROFIT_HIST = []
    for arg_i in range(1, (len(sys.argv) // 3) + 2, 2):
        _config = sys.argv[arg_i].split('\\')
        AGENT_METHOD = _config[-2]
        CURRENCY_PAIR = _config[-1]

        theMarket = Market(
            data_path="data/%s_Candlestick_4_Hour_BID_01.12.2018-31.12.2018.csv"
            % CURRENCY_PAIR)  #, indicators={'ADX': 12})
        MyRecord = Record()
        MyOrderManager = OrderManager(market=theMarket, record=MyRecord)
        MyTrader = SureFireTrader(orderManager=MyOrderManager)

        SLTP_pips = [20, 25, 30]
        start_order_type = ['BUY', 'SELL']
        max_level_limit = [2, 3, 4]
        window_size = 12

        # Create a RL agent
        if AGENT_METHOD != "constant":
            with open("config/%s.json" % AGENT_METHOD, 'r') as fp:
                agent_config = json.load(fp=fp)
            with open("config/conv2d.json", 'r') as fp:
                network_config = json.load(fp=fp)
            agent = Agent.from_spec(
                spec=agent_config,
                kwargs=dict(
                    states=dict(type='float',
                                shape=(window_size, window_size,
                                       4)),  #[Open, High, Low, Close]
                    actions=dict(
                        SLTP_pips=dict(
                            type='int',
                            num_actions=len(SLTP_pips)),  #[20,25,30]
                        start_order_type=dict(
                            type='int', num_actions=len(
                                start_order_type)),  #['BUY','SELL']
                        max_level_limit=dict(
                            type='int',
                            num_actions=len(max_level_limit))  #[2,3,4,5]
                    ),
                    network=network_config))
            the_episode = int(sys.argv[arg_i + 1])
            agent.restore_model(sys.argv[arg_i] + '/%04d' % the_episode)

        else:
            agent = ConstantAgent(
                states=dict(type='float',
                            shape=(window_size, window_size,
                                   4)),  #[Open, High, Low, Close]
                actions=dict(
                    SLTP_pips=dict(type='int',
                                   num_actions=len(SLTP_pips)),  #[20,25,30]
                    start_order_type=dict(
                        type='int',
                        num_actions=len(start_order_type)),  #['BUY','SELL']
                    max_level_limit=dict(
                        type='int', num_actions=len(max_level_limit))  #[2,3,4]
                ),
                action_values={
                    'SLTP_pips': 2,
                    'max_level_limit': 2,
                    'start_order_type': 0
                })
            the_episode = 0

        profit_history = []
        idle_count = 0
        round_count = 0
        episode_end = False
        max_idle_limit = 12  #future action
        MyRecord.reset()
        MyOrderManager.reset()
        theMarket.reset(start_index=window_size)

        #pbar = tqdm()
        while (theMarket.next()):  #main loop, essential

            #pbar.update(1) # simple-GUI

            ################### ROUTINES ###################
            MyOrderManager.orders_check()  #routine, after market.next
            trade_status, other_detail = MyTrader.status_check(
            )  #routine, after orders_check
            ################################################

            ################### GET STATE ##################
            ohlc = theMarket.get_ohlc(size=window_size)
            indicators = theMarket.get_indicators(size=window_size)
            O, H, L, C = gaf_encode(ohlc['Open']), gaf_encode(ohlc['High']), \
                            gaf_encode(ohlc['Low']),gaf_encode(ohlc['Close'])
            #ADX = gaf_encode(indicators['ADX'])
            state = np.stack((O, H, L, C), axis=-1)
            ################################################

            ################## TAKE ACTION #################
            if trade_status == 'TRADE_OVER':

                ############ GET REWARD & TRAIN ################

                action = agent.act(state)  # Get prediction from agent, execute
                SL_pip = SLTP_pips[action['SLTP_pips']] * 2
                TP_pip = SLTP_pips[action['SLTP_pips']]
                MyTrader.set_max_level(
                    max_level_limit[action['max_level_limit']])
                first_order_type = start_order_type[action['start_order_type']]
                ################################################

                MyTrader.new_trade(SL_pip=SL_pip,
                                   TP_pip=TP_pip,
                                   start_order_type=first_order_type)

                round_count += 1
                idle_count = 0
                logging.info(
                    "NewTradeStarted: current net profit=%f (price@%f)" %
                    (MyRecord.get_net_profit(), theMarket.get_market_price()))

            elif trade_status == 'ADD_ORDER':
                last_order = MyTrader.get_orders_detail()[-1]
                if last_order['order_type'] == 'BUY':
                    price = last_order['price'] - theMarket.get_pip(TP_pip)
                elif last_order['order_type'] == 'SELL':
                    price = last_order['price'] + theMarket.get_pip(TP_pip)
                MyTrader.add_reverse_order(price=price,
                                           SL_pip=SL_pip,
                                           TP_pip=TP_pip)
                idle_count = 0

            elif trade_status == 'ERROR':
                logging.warning("SureFireError: order issues...")

            elif trade_status == 'NONE':
                idle_count += 1
                if idle_count >= max_idle_limit:

                    action = agent.act(
                        state)  # Get prediction from agent, execute
                    SL_pip = SLTP_pips[action['SLTP_pips']] * 2
                    TP_pip = SLTP_pips[action['SLTP_pips']]
                    MyTrader.set_max_level(
                        max_level_limit[action['max_level_limit']])
                    first_order_type = start_order_type[
                        action['start_order_type']]

                    MyTrader.new_trade(SL_pip=SL_pip,
                                       TP_pip=TP_pip,
                                       start_order_type=first_order_type)
                    idle_count = 0
                    logging.info(
                        "NewTradeStarted: current net profit=%f (price@%f)" %
                        (MyRecord.get_net_profit(),
                         theMarket.get_market_price()))
            ################################################

            profit_history.append(MyRecord.get_net_profit() *
                                  10000)  #for plotting

        #pbar.close()
        my_details = MyRecord.show_details()
        print("Rounds of Tradings: %d\n" % round_count)
        print('---')

        PROFIT_HIST.append(profit_history)

    if len(sys.argv) > 5:
        df = pd.read_csv(sys.argv[5])
        baseline = df['hist'].tolist()
        plt.plot(range(len(baseline)), baseline, color='purple', linestyle=':')
        plt.plot(range(len(PROFIT_HIST[0])), PROFIT_HIST[0])
        plt.plot(range(len(PROFIT_HIST[1])), PROFIT_HIST[1])
        plt.xlabel('timestep')
        plt.ylabel('accumulated return')
        plt.legend([
            'baseline', sys.argv[1].split('\\')[-2],
            sys.argv[3].split('\\')[-2]
        ],
                   loc='lower right',
                   fontsize='x-large')
        plt.show()

    else:
        plt.plot(range(len(profit_history)), profit_history)
        plt.xlabel('timestep')
        plt.ylabel('accumulated return')
        plt.show()
        pd.DataFrame({
            'hist': profit_history
        }).to_csv('profit_history_test.csv', index=False)
Пример #3
0
def OF():
    OI = Market(
        data_path="data/%s_Candlestick_4_Hour_BID_01.08.2018-30.11.2018.csv" %
        Om)
    Oa = Record()
    Oo = OrderManager(market=OI, record=Oa)
    OS = SureFireTrader(orderManager=Oo)
    OP = [20, 25, 30]
    OH = ['BUY', 'SELL']
    Oy = [2, 3, 4]
    Oc = 12
    OR = ConstantAgent(states=Og(type='float', shape=(Oc, Oc, 4)),
                       actions=Og(SLTP_pips=Og(type='int', num_actions=OQ(OP)),
                                  start_order_type=Og(type='int',
                                                      num_actions=OQ(OH)),
                                  max_level_limit=Og(type='int',
                                                     num_actions=OQ(Oy))),
                       action_values={
                           'SLTP_pips': 0,
                           'max_level_limit': 0,
                           'start_order_type': 0
                       })
    if not Ol.exists("save_model/constant/trades"):
        Op("save_model/constant/trades")
    if not Ol.exists('save_model/constant/0000'):
        Op('save_model/constant/0000')
    OR.save_model('save_model/constant/0000/model')
    OM = []
    OW = []
    OL = []
    Os = 0
    OX = 0
    OB = OY
    OK = 12
    Oa.reset()
    Oo.reset()
    OI.reset(start_index=Oc)
    OD = tqdm()
    while (OI.next()):
        OD.update(1)
        Oo.orders_check()
        OJ, Oz = OS.status_check()
        Oj = OI.get_ohlc(size=Oc)
        Ok = OI.get_indicators(size=Oc)
        O, H, L, C = gaf_encode(Oj['Open']), gaf_encode(
            Oj['High']), gaf_encode(Oj['Low']), gaf_encode(Oj['Close'])
        Or = On((O, H, L, C), axis=-1)
        if OJ == 'TRADE_OVER':
            if OI.get_current_index() > Oc:
                Of = (Oa.get_net_profit() - OW[-1]) / OI.get_pip()
                Ov = 1.0 - 0.1 * OQ(Oz)
                if Of > 0:
                    Ou = Of * Ov
                else:
                    if OQ(Oz) == 0:
                        Ou = 0
                    else:
                        Ou = -Ow(Oz[0]['TP'] - Oz[0]['price']) / OI.get_pip()
                if OI.get_current_index(
                ) >= OI.get_data_length() - OK * Oy[-1]:
                    OB = OU
                OR.observe(reward=Ou, terminal=OB)
                OL.append(Ou)
                if OB == OU:
                    OD.close()
                    OM.append(OL)
                    break
            OT = OR.act(Or)
            OE = OP[OT['SLTP_pips']] * 2
            OG = OP[OT['SLTP_pips']]
            OS.set_max_level(Oy[OT['max_level_limit']])
            Oq = OH[OT['start_order_type']]
            OS.new_trade(SL_pip=OE, TP_pip=OG, start_order_type=Oq)
            OX += 1
            Os = 0
            Ot("NewTradeStarted: current net profit=%f (price@%f)" %
               (Oa.get_net_profit(), OI.get_market_price()))
        elif OJ == 'ADD_ORDER':
            OA = OS.get_orders_detail()[-1]
            if OA['order_type'] == 'BUY':
                Oi = OA['price'] - OI.get_pip(OG)
            elif OA['order_type'] == 'SELL':
                Oi = OA['price'] + OI.get_pip(OG)
            OS.add_reverse_order(price=Oi, SL_pip=OE, TP_pip=OG)
            Os = 0
        elif OJ == 'ERROR':
            Ox("SureFireError: order issues...")
        elif OJ == 'NONE':
            Os += 1
            if Os >= OK:
                Of = (Oa.get_net_profit() - OW[-1]) / OI.get_pip()
                Ov = 1.0 - 0.1 * OQ(Oz)
                if Of > 0:
                    Ou = Of * Ov
                else:
                    if OQ(Oz) == 0:
                        Ou = 0
                    else:
                        Ou = -Ow(Oz[0]['TP'] - Oz[0]['price']) / OI.get_pip()
                if OI.get_current_index(
                ) >= OI.get_data_length() - OK * Oy[-1]:
                    OB = OU
                OR.observe(reward=Ou, terminal=OB)
                OL.append(Ou)
                if OB == OU:
                    OD.close()
                    OM.append(OL)
                    break
                OT = OR.act(Or)
                OE = OP[OT['SLTP_pips']] * 2
                OG = OP[OT['SLTP_pips']]
                OS.set_max_level(Oy[OT['max_level_limit']])
                Oq = OH[OT['start_order_type']]
                OS.new_trade(SL_pip=OE, TP_pip=OG, start_order_type=Oq)
                Os = 0
                Ot("NewTradeStarted: current net profit=%f (price@%f)" %
                   (Oa.get_net_profit(), OI.get_market_price()))
        OW.append(Oa.get_net_profit())
    with OV('save_model/constant/trades/episode_0000.pkl', 'wb') as f:
        ON(Oa.get_history(), f, protocol=-1)
    with OV('save_model/constant/trades/profit_history.pkl', 'wb') as f:
        ON(OW, f, protocol=-1)
    with OV('save_model/constant/trades/reward_history.pkl', 'wb') as f:
        ON(OM, f, protocol=-1)
    Oa.show_details()
Пример #4
0
def main():
    
    AGENT_METHOD = sys.argv[1] # "ppo"
    CURRENCY_PAIR = sys.argv[2] # "EURUSD"

    theMarket = Market(data_path="data/%s_Candlestick_4_Hour_BID_01.12.2018-31.12.2018.csv"%CURRENCY_PAIR)#, indicators={'ADX': 12})
    MyRecord = Record()
    MyOrderManager = OrderManager(market=theMarket, record=MyRecord)
    MyTrader = SureFireTrader(orderManager=MyOrderManager)

    SLTP_pips = [20,25,30]
    start_order_type = ['BUY','SELL']
    max_level_limit = [2,3,4]
    window_size = 12
    
    output_record = {'episode':[], 'total_trades': [], 'win_trades': [],
                    'lose_trades': [], 'profit_factor': [], 'net_profit': [],
                    'max_drawdown': [], 'trading_rounds': []}
                    
    if AGENT_METHOD != "constant":                
        iter_range = range(0,100+1,100)
    else:
        iter_range = range(1)
        
    for the_episode in iter_range:
        # Create a RL agent
        if AGENT_METHOD != "constant":
            with open("config/%s.json"%AGENT_METHOD, 'r') as fp:
                agent_config = json.load(fp=fp)
            with open("config/conv2d.json", 'r') as fp:
                network_config = json.load(fp=fp)
            agent = Agent.from_spec(
                spec=agent_config,
                kwargs=dict(
                    states=dict(type='float', shape=(window_size,window_size,4)),               #[Open, High, Low, Close]
                    actions=dict(
                        SLTP_pips=dict(type='int', num_actions=len(SLTP_pips)),                 #[20,25,30]
                        start_order_type=dict(type='int', num_actions=len(start_order_type)),   #['BUY','SELL']
                        max_level_limit=dict(type='int', num_actions=len(max_level_limit))      #[2,3,4,5]
                    ),
                    network=network_config
                )

            )
            agent.restore_model("save_model"+"/"+AGENT_METHOD+"/"+'%04d'%the_episode)
        else:
            agent = ConstantAgent(
                states=dict(type='float', shape=(window_size,window_size,4)),               #[Open, High, Low, Close]
                actions=dict(
                    SLTP_pips=dict(type='int', num_actions=len(SLTP_pips)),                 #[20,25,30]
                    start_order_type=dict(type='int', num_actions=len(start_order_type)),   #['BUY','SELL']
                    max_level_limit=dict(type='int', num_actions=len(max_level_limit))      #[2,3,4]
                ),
                action_values={'SLTP_pips': 2, 'max_level_limit': 2, 'start_order_type': 0}
            )

        profit_history = []
        idle_count = 0
        round_count = 0
        episode_end = False
        max_idle_limit = 12 #future action
        MyRecord.reset()
        MyOrderManager.reset()
        theMarket.reset(start_index=window_size)
        
        #pbar = tqdm()
        while(theMarket.next()): #main loop, essential

            #pbar.update(1) # simple-GUI
            
            ################### ROUTINES ################### 
            MyOrderManager.orders_check() #routine, after market.next
            trade_status, other_detail = MyTrader.status_check() #routine, after orders_check
            ################################################


            ################### GET STATE ##################
            ohlc = theMarket.get_ohlc(size=window_size)
            indicators = theMarket.get_indicators(size=window_size)
            O, H, L, C = gaf_encode(ohlc['Open']), gaf_encode(ohlc['High']), \
                            gaf_encode(ohlc['Low']),gaf_encode(ohlc['Close'])
            #ADX = gaf_encode(indicators['ADX'])
            state = np.stack((O,H,L,C),axis=-1)
            ################################################


            ################## TAKE ACTION #################
            if trade_status == 'TRADE_OVER':
                
                ############ GET REWARD & TRAIN ################

                action = agent.act(state) # Get prediction from agent, execute
                SL_pip = SLTP_pips[action['SLTP_pips']]*2
                TP_pip = SLTP_pips[action['SLTP_pips']]
                MyTrader.set_max_level(max_level_limit[action['max_level_limit']])
                first_order_type = start_order_type[action['start_order_type']]
                ################################################

                MyTrader.new_trade(SL_pip=SL_pip, TP_pip=TP_pip, start_order_type=first_order_type)

                round_count += 1
                idle_count = 0
                logging.info("NewTradeStarted: current net profit=%f (price@%f)"%(MyRecord.get_net_profit(), theMarket.get_market_price()))
            
            elif trade_status == 'ADD_ORDER':
                last_order = MyTrader.get_orders_detail()[-1]
                if last_order['order_type'] == 'BUY':
                    price = last_order['price'] - theMarket.get_pip(TP_pip)
                elif last_order['order_type'] == 'SELL':
                    price = last_order['price'] + theMarket.get_pip(TP_pip)
                MyTrader.add_reverse_order(price=price, SL_pip=SL_pip, TP_pip=TP_pip)
                idle_count = 0
            
            elif trade_status == 'ERROR':
                logging.warning("SureFireError: order issues...")
            
            elif trade_status == 'NONE':
                idle_count += 1
                if idle_count >= max_idle_limit:
                    
                    action = agent.act(state) # Get prediction from agent, execute
                    SL_pip = SLTP_pips[action['SLTP_pips']]*2
                    TP_pip = SLTP_pips[action['SLTP_pips']]
                    MyTrader.set_max_level(max_level_limit[action['max_level_limit']])
                    first_order_type = start_order_type[action['start_order_type']]
                    

                    MyTrader.new_trade(SL_pip=SL_pip, TP_pip=TP_pip, start_order_type=first_order_type)
                    idle_count = 0
                    logging.info("NewTradeStarted: current net profit=%f (price@%f)"%(MyRecord.get_net_profit(), theMarket.get_market_price()))
            ################################################

        
            profit_history.append(MyRecord.get_net_profit()) #for plotting
        
        #pbar.close()
        my_details = MyRecord.show_details()
        print("Rounds of Tradings: %d\n"%round_count)
        print('---')
        
        output_record['episode'].append(the_episode)
        output_record['trading_rounds'].append(round_count)
        for k in my_details:
            output_record[k].append(my_details[k])
        
        plt.plot(range(len(profit_history)), profit_history)
        plt.show()
        
        
    for k in output_record:
        plt.plot(output_record['episode'], output_record[k])
        plt.title(k)
        plt.show()
    
    pd.DataFrame(output_record).to_csv('test_detail-episode.csv', index=False)
Пример #5
0
def fi():
    fj = fn[1].split('\\')
    fd = fj[-2]
    fW = fj[-1]
    fh = Market(
        data_path="data/%s_Candlestick_4_Hour_BID_01.12.2018-31.12.2018.csv" %
        fW)
    fs = Record()
    fr = OrderManager(market=fh, record=fs)
    fE = SureFireTrader(orderManager=fr)
    fI = [20, 25, 30]
    fx = ['BUY', 'SELL']
    fB = [2, 3, 4]
    fY = 12
    fP = {
        'episode': [],
        'total_trades': [],
        'win_trades': [],
        'lose_trades': [],
        'profit_factor': [],
        'net_profit': [],
        'max_drawdown': [],
        'trading_rounds': []
    }
    if fd != "constant":
        fA = fR(0, 100 + 1, 100)
    else:
        fA = fR(1)
    for fa in fA:
        if fd != "constant":
            with fD("config/%s.json" % fd, 'r') as fp:
                fk = fV(fp=fp)
            with fD("config/conv2d.json", 'r') as fp:
                fF = fV(fp=fp)
            fo = fL(spec=fk,
                    kwargs=fy(states=fy(type='float', shape=(fY, fY, 4)),
                              actions=fy(
                                  SLTP_pips=fy(type='int', num_actions=fm(fI)),
                                  start_order_type=fy(type='int',
                                                      num_actions=fm(fx)),
                                  max_level_limit=fy(type='int',
                                                     num_actions=fm(fB))),
                              network=fF))
            fo.restore_model(fn[1] + '/%04d' % fa)
        else:
            fo = ConstantAgent(
                states=fy(type='float', shape=(fY, fY, 4)),
                actions=fy(SLTP_pips=fy(type='int', num_actions=fm(fI)),
                           start_order_type=fy(type='int', num_actions=fm(fx)),
                           max_level_limit=fy(type='int', num_actions=fm(fB))),
                action_values={
                    'SLTP_pips': 2,
                    'max_level_limit': 2,
                    'start_order_type': 0
                })
        fQ = []
        fz = 0
        fN = 0
        fK = fp
        fg = 12
        fs.reset()
        fr.reset()
        fh.reset(start_index=fY)
        while (fh.next()):
            fr.orders_check()
            fw, fl = fE.status_check()
            fT = fh.get_ohlc(size=fY)
            fc = fh.get_indicators(size=fY)
            O, H, L, C = gaf_encode(fT['Open']), gaf_encode(
                fT['High']), gaf_encode(fT['Low']), gaf_encode(fT['Close'])
            fG = fU((O, H, L, C), axis=-1)
            if fw == 'TRADE_OVER':
                fX = fo.act(fG)
                fS = fI[fX['SLTP_pips']] * 2
                ft = fI[fX['SLTP_pips']]
                fE.set_max_level(fB[fX['max_level_limit']])
                fb = fx[fX['start_order_type']]
                fE.new_trade(SL_pip=fS, TP_pip=ft, start_order_type=fb)
                fN += 1
                fz = 0
                fq("NewTradeStarted: current net profit=%f (price@%f)" %
                   (fs.get_net_profit(), fh.get_market_price()))
            elif fw == 'ADD_ORDER':
                fO = fE.get_orders_detail()[-1]
                if fO['order_type'] == 'BUY':
                    fH = fO['price'] - fh.get_pip(ft)
                elif fO['order_type'] == 'SELL':
                    fH = fO['price'] + fh.get_pip(ft)
                fE.add_reverse_order(price=fH, SL_pip=fS, TP_pip=ft)
                fz = 0
            elif fw == 'ERROR':
                fJ("SureFireError: order issues...")
            elif fw == 'NONE':
                fz += 1
                if fz >= fg:
                    fX = fo.act(fG)
                    fS = fI[fX['SLTP_pips']] * 2
                    ft = fI[fX['SLTP_pips']]
                    fE.set_max_level(fB[fX['max_level_limit']])
                    fb = fx[fX['start_order_type']]
                    fE.new_trade(SL_pip=fS, TP_pip=ft, start_order_type=fb)
                    fz = 0
                    fq("NewTradeStarted: current net profit=%f (price@%f)" %
                       (fs.get_net_profit(), fh.get_market_price()))
            fQ.append(fs.get_net_profit())
        fe = fs.show_details()
        fv("Rounds of Tradings: %d\n" % fN)
        fv('---')
        fP['episode'].append(fa)
        fP['trading_rounds'].append(fN)
        for k in fe:
            fP[k].append(fe[k])
    '''
    for k in output_record:
        plt.plot(output_record['episode'], output_record[k])
        plt.title(k)
        plt.show()
    '''
    fC(fP).to_csv('test_detail-episode.csv', index=fp)