I am now working on the smart contract for secondary market, which is the stock negotiation. For example, user A wants to buy a stock, user sets the acceptable price and the amount. The order will be put into the "Buy array", waiting for the match price. If user A wants to sell a stock, just as the procedure of buying a stock, user sets the price and the amount to sell. What I am thinking now is creating a struct Order as follow:
struct Order {
uint256 orderno;
uint256 time;
address from;
uint256 price;
uint256 amount;
}
Using struct, we can have the instance of Buy and Sell strcut
Order[] public Buy
Order[] public Sell
and we can create function of Buy and Sell. //user put buy order
function buy(address _from,uint256 _price, uint256 _amount) onlyOwner public {
uint256 dealamount;
uint256 dealprice;
for(uint256 count = 0;count <s.length;count++)
{
if(_amount==0) {
break;
}
if(_price>=s[count].price)
{
dealprice = s[count].price;
if(_amount >= s[count].amount){
dealamount = s[count].amount;
}
else {
dealamount = _amount;
}
s[count].amount-= dealamount;
_amount-=dealamount;
sectransfer(this,_from,dealamount,dealprice);
deal(this,s[count].from,_from,now,dealamount,dealprice);//event
sellmatch[s[count].price]-=dealamount;
}
}
removezerosell();
//no deal, push into buy struct
if (_amount > 0)
{
insertbuy(Order(orderno,now, _from, _price, _amount));
//b.push(Order(orderno,now, _from, _price, _amount));
//sortbuy();
buymatch[_price] += _amount;
orderno++;
}
}
function sell(address _from,uint256 _price, uint256 _amount) onlyOwner public{
//if(msg.sender != owner) return;
//check user have enough token
if(balanceOf[_from] < _amount ) return;
temptransfer(_from,this,_amount);
uint256 dealamount;
uint256 dealprice;
for(uint256 count=0;count<b.length;count++)
{
if(_amount==0){
break;
}
if(_price <= b[count].price){
dealprice = _price;
if(_amount >= b[count].amount){
dealamount = b[count].amount;
}
else {
dealamount = _amount;
}
b[count].amount -= dealamount;
_amount -= dealamount;
sectransfer(this,b[count].from,dealamount,dealprice);
deal(this,_from,b[count].from,now,dealamount,dealprice);
buymatch[b[count].price]-=dealamount;
}
}
removezerobuy();
if (_amount > 0)
{
insertsell(Order(orderno,now, _from, _price, _amount));
//s.push(Order(orderno,now, _from, _price, _amount));
sellmatch[_price] += _amount;
orderno++;
}
}
Is there a better way of doing the concept of trading stock and the secondary market? Or what can I improve the buy and sell function?