step by step开发一个简易股票交易系统(一)---万事开头简

前面写的有些乱,重新整理一下代码和文档
step 1:先考虑最简化情况,只有一只股票,并且不考虑股票数量,没有考虑挂单时间顺序,使用一个list存放买卖交易队列,只要买/卖的价格高于/低于当前任意一个交易挂单,即可成交。
-module(stock1).
-export([start/0,buy/2,sell/2]).

start()->
register(stock,spawn(fun()->loop([])end)).

buy(Price,Name) ->
stock!{buy,self(),Price,Name},
receive
{Pid,Response,Sell}->
{Response,Sell}
end.

sell(Price,Name) ->
stock!{sell,self(),Price,Name},
receive
{Pid,Response,Buy}->
{Response,Buy}
end.

loop(L)->
receive
{buy,Pid,Price,Name}->
case lookupsell({Price,none},L) of
{Price,none}->
Pid!{self(),hangup,waiting},
L2=[{buy,Price,Name}|L],
loop(L2);

{Price1,Sell}->
Pid!{self(),ok,Sell},
L2=remove({sell,Price1,Sell},L),
loop(L2)
end;
{sell,Pid,Price,Name}->
case lookupbuy({Price,none},L) of
{Price,none}->
Pid!{self(),hangup,waiting},
L2=[{sell,Price,Name}|L],
loop(L2);
{Price1,Buy}->
Pid!{self(),ok,Buy},
L2=remove({buy,Price1,Buy},L),
loop(L2)

end
end.

lookupsell({Price,Buy},[{sell,Price1,Name}|T]) ->
if
Price>Price1 -> lookupsell({Price1,Name},T);
true->lookupsell({Price,Buy},T)
end;
lookupsell({Price,Buy},[{buy,_,_}|T])->lookupsell({Price,Buy},T);
lookupsell({Price,Buy},[])->{Price,Buy}.

lookupbuy({Price,Sell},[{buy,Price1,Name}|T]) ->
if
Price<Price1 -> lookupbuy({Price1,Name},T);
true->lookupbuy({Price,Sell},T)
end;
lookupbuy({Price,Sell},[{sell,_,_}|T])->lookupbuy({Price,Sell},T);
lookupbuy({Price,Sell},[])->{Price,Sell}.

remove(Trade,L)-> [X||X<-L,X/=Trade].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值